<?php /** * 建造者模式 * ------------- * @author zhaoxuejie <zxj198468@gmail.com> * @package design pattern * @version v1.0 2011-12-14 */ /*产品角色-在指导者的指导下由建造者所创建的那个复杂的对象*/ class Person { private $head; private $body; private $foot; //头 public function getHead() { return $this->head; } public function setHead($head) { $this->head = $head; } //体 public function getBody() { return $this->body; } public function setBody($body) { $this->body = $body; } //脚 public function getFoot() { return $this->foot; } public function setFoot($foot) { $this->foot = $foot; } } /*抽象建造者-创建一个product对象的各个部件指定抽象接口*/ interface PersonBuilder { public function buildHead(); public function buildBody(); public function buildFoot(); public function getResult();//产品返还方法 } /*具体建造者-实现接口*/ class ConcreteBuilder implements PersonBuilder { private $person; function __construct() { $this->person = new Person(); } function buildHead() { $this->person->setHead('建造头……'); } function buildBody() { $this->person->setBody('建造身体……'); } function buildFoot() { $this->person->setFoot('建造脚……'); } function getResult() { return $this->person; } } /*导演者-指导者导演者角色与客户端直接打交道,它理解客户端的业务逻辑, 将客户端创建产品的请求拆分成对产品组成部分的请求, 然后调用具体产品角色执行建造操作。它分离了客户端与具体建造者 */ class Director { public function __construct(ConcreteBuilder $builder) { $builder->buildHead(); $builder->buildBody(); $builder->buildFoot(); } } /*客户端*/ class Client { public static function main() { $builder = new ConcreteBuilder(); $director = new Director($builder); $person = $builder->getResult(); echo $person->getHead(); echo $person->getBody(); echo $person->getFoot(); } } Client::main(); ?>