C3:建造者模式 Builder
将一个复杂对象的创建与表示分离,使得同样的构建过程可以创建不同的表示.
应用场景:
A.创建这个对象通常需要较多的参数,才能完整的表示该对象.
B.类的各个组成部分的具体实现类或算法经常面临变化,但将他们组合在一起却相对稳定,提供一种封装机制 将稳定的组合算法于易变的各个组成部分隔离开来.
C.不同的创建方式或参数,可以在同一个类上表示相对不同的对象.(如创建一个person类,年龄小的速度快的为年轻人,年龄大的速度慢的为老年人)
为什么需要建造者模式:
* 1.创建这个对象,通常比较复杂,需要给予过多的参数,才能完成创建.
* 2.对象的生成时可根据初始化的顺序或数据不同,而生成不同角色
UML图
示例代码一:
class Person { protected $age; protected $speed; public function setAge($age) { $this->age = $age; } public function setSpeed($speed) { $this->speed = $speed; } public function getAge() { return $this->age; } public function getSpeed() { return $this->speed; } } abstract class Builder { protected $person; public function __construct(Person $person) { $this->person = $person; } public function getPerson() { return $this->person; } abstract public function setAge(); abstract public function setSpeed(); } class OldManBuilder extends Builder { public function setAge() { $this->person->setAge(70); } public function setSpeed() { $this->person->setSpeed(10); } } class ChildBuilder extends Builder { public function setAge() { $this->person->setAge(10); } public function setSpeed() { $this->person->setSpeed(10); } } // 建造指挥者 class Director { private $builder; public function __construct(Builder $builder) { $this->builder = $builder; } public function built() { $this->builder->setAge(); $this->builder->setSpeed(); } } // 建造 $old = new OldManBuilder(new Person()); $director = new Director($old); $director->built(); $person = $old->getPerson(); echo $person->getAge();
示例代码二:
class Person { private $name, $age; public function setName($name){ $this->name = $name; } public function setAge($age) { $this->age = $name; } } 如果我们要使该类"完整",必须调用setName和setAge. class Builder { private $person; private $configs public function __construct($configs) { $this->person = new Person(); $this->configs = $configs; } // 将person的多个方法都放在此方法中执行. public function build() { $this->person->setName($config['name']); $this->person->setAge($config['age']); } public function getPerson() { return $this->person; } } // 调用 $build = new Build(array('name' => 'php', 'age' => 10)); $build->build(); $person = $person->getPerson();
ps:建造者模式依然是创建型模式之一,依然强调的是一个类的创建.这是它区别于外观模式的区别.