建造者模式

建造者模式

参考:人人都会设计模式—建造者模式–Builder
建造者模式

建造者,创建一个复杂对象的接口。以同样的的过程创建不同的产品

主要包含如下角色

  • 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() );
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值