建造者模式

2017-05-29  本文已影响4人  散装咖啡
/* 
builder模式
    将一个复杂对象的构建与它的表示分离,使用同样的构建过程可以创建不同的表示
    使用建造者模式的好处
    1.使用建造者模式可以使客户端不必知道产品内部组成的细节。
    2.具体的建造者类之间是相互独立的,对系统的扩展非常有利。
    3.由于具体的建造者是独立的,因此可以对建造过程逐步细化,而不对其他的模块产生任何影响。

    使用建造者模式的场合:
    1.创建一些复杂的对象时,这些对象的内部组成构件间的建造顺序是稳定的,但是对象的内部组成构件面临着复杂的变化。
    2.要创建的复杂对象的算法,独立于该对象的组成部分,也独立于组成部分的装配方法时。

*/
    class Product
    {
        public $_type = null;
        public $_size = null;
        public $_color = null;
        
        public function setType($type)
        {
            echo "set product type<br/>";
            $this->_type =$type;
        }
        
        public function setSize($size)
        {
            echo"set product size<br/>";
            $this->_size =$size;
        }
        
        public function setColor($color)
        {
            echo"set product color<br/>";
            $this->_color =$color;
        }
    }
    
    $config = [
        'type'  => 'shirt',
        'size'  => 'xl',
        'color' => 'red',
    ];
    
        // 没有使用 bulider 以前的处理
        $oProduct = new Product();
        $oProduct->setType($config['type']);
        $oProduct->setSize($config['size']);
        $oProduct->setColor($config['color']);
        
    // 创建一个 builder 类
    class ProductBuilder
    {
        public $_config = null;
        public $_object = null;
        public function __construct($config)
        {
            $this->_object =new Product();
            $this->_config =$config;
        }
        
        public function build()
        {
            echo"--- in builder---<br/>";
            $this->_object->setType($this->_config['type']);
            $this->_object->setSize($this->_config['size']);
            $this->_object->setColor($this->_config['color']);
        }
        
        public function getProduct()
        {
            return $this->_object;
        }
    }

    $objBuilder=new ProductBuilder($config);
    $objBuilder->build();
    $objProduct=$objBuilder->getProduct();

参考文章 https://wenku.baidu.com/view/b4c78b4702768e9951e738fb.html

上一篇 下一篇

猜你喜欢

热点阅读