_name = $name; } public function setAge($age){ $this->_age = $age; } public function setSex($sex){ $this->_sex = $sex; }}class UserBuilder{ protected $_user; protected $_configs; public function __construct($config){ $this->_user = new User(); $this->_configs = $config; } public function builder(){ $this->_user->setName($this->_configs["name"]); $this->_user->setAge($this->_configs["age"]); $this->_user->setSex($this->_configs["sex"]); } public function getUser(){ return $this->_user; }}//避免重复$config = array("name"=>"beck","age"=>18,"sex"=>1);//如果没有builder$user = new User();$user->setName($this->_configs["name"]);$user->setAge($this->_configs["age"]);$user->setSex($this->_configs["sex"]);$config = array("name"=>"beck_new","age"=>38,"sex"=>2);//如果没有builder$user2 = new User();$user2->setName($this->_configs["name"]);$user2->setAge($this->_configs["age"]);$user2->setSex($this->_configs["sex"]);//如果有builder,去除重复$builder = new UserBuilder($config);$builder->builder();print_r($builder->getUser());
建造者模式:把一个类的对象的构建交给另外一个类。