建造者模式
建造者,创建一个复杂对象的接口。以同样的的过程创建不同的产品
主要包含如下角色
- Builder:抽象建造者
- ConcreteBuilder:具体建造者
- Director:指挥者
- Product:产品角色
网上看到有两种代码形式一种就是我粘贴出来的,另一种就是创建不同的建造者,来实现产品 客户端 有新的需求就添加新的工具人,有指挥家同一生成,这样就有一个问题,生成的产品必须基于产品角色。但是容易扩展 符合“开闭原则”
//产品
class people
{
private $height;
private $hand;
private $leg;
private $body;
public function setHeight($height)
{
$this->height = $height;
}
public function getHeight($height)
{
return $this->height;
}
public function setHand($hand)
{
$this->hand = $hand;
}
public function getHand($hand)
{
return $this->hand;
}
public function setLeg($leg)
{
$this->leg = $leg;
}
public function getLeg($leg)
{
return $this->leg;
}
public function setBody($body)
{
$this->body = $body;
}
public function getBody($body)
{
return $this->body;
}
}
interface BuilderInterface
{
public function createPeople();
public function addHeight($str);
public function addHand($str);
public function addLeg($str);
public function addBody($str);
public function getPeople();
}
// 工具人
class ManPeople implements BuilderInterface
{
public $people;
public function createPeople()
{
$this->people = new people();
}
public function addHeight($str)
{
$this->people->setHeight( $str );
}
public function addHand($str)
{
$this->people->setHand( $str );
}
public function addLeg($str)
{
$this->people->setLeg( $str );
}
public function addBody($str)
{
$this->people->setBody( $str );
}
public function getPeople()
{
return $this->people;
}
}
class PeopleDirector
{
private $build;
public function __construct(ManPeople $manPeople)
{
$this->build = $manPeople;
}
// 指挥
public function buildPeople(array $arr)
{
$this->build->createPeople();
$this->build->addHeight( $arr['height'] );
$this->build->addHand( $arr['hand'] );
$this->build->addLeg( $arr['leg'] );
$this->build->addBody( $arr['body'] );
return $this->build->getPeople();
}
}
$people = new PeopleDirector( new ManPeople() );