建造者模式->代码示例

<?php

interface Builder{
    public function head();

    public function body();

    public function foot();

    public function hand();
}

class Director {

    private static $_instance = null;
    private $builder = null;
    private function __construct(Builder $builder){
        $this->builder = $builder;
    }
    public static function getInstance(Builder $builder){
        if(self::$_instance == null){
            self::$_instance = new Director($builder);
        }
        return self::$_instance;
    }
    private function createHead(Builder $builder = null){
        if($builder){
            return $builder->head();
        }else{
            return $this->builder->head();
        }
    }
    private function createBody(Builder $builder = null){
        if($builder){
            return $builder->body();
        }else{
            return $this->builder->body();
        }
    }
    private function createHand(Builder $builder = null){
        if($builder){
            return $builder->hand();
        }else{
            return $this->builder->hand();
        }
    }
    private function createFoot(Builder $builder = null){
        if($builder){
            return $builder->foot();
        }else{
            return $this->builder->foot();
        }
    }
    public function startCreate(){
        $this->createFoot();
        $this->createBody();
        $this->createHand();
        $this->createHead();
        echo "\n人造出来嘞";
    }
}

class zhangsan implements Builder{

    public function foot(){
        echo "张三的脚被造出来了\n";
    }

    public function hand(){
        echo "张三的手被造出来嘞\n";
    }

    public function head(){
        echo "张三的头被造出来了\n";
    }

    public function body(){
        echo "张三的身体被造出来嘞\n";
    }
}

class lisi implements Builder{

    public function foot(){
        echo "李四的脚被造出来了\n";
    }

    public function hand(){
        echo "李四的手被造出来嘞\n";
    }

    public function head(){
        echo "李四的头被造出来了\n";
    }

    public function body(){
        echo "李四的身体被造出来嘞\n";
    }
}

$builder = Director::getInstance(new zhangsan());
$builder->startCreate();
$builder = Director::getInstance(new lisi());
$builder->startCreate();

 

转载于:https://www.cnblogs.com/Super-Man/p/4384310.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值