zoukankan      html  css  js  c++  java
  • php-建造者模式(Builder)解析

    其与抽象模式相类似,都可以创建复杂的对象,但是抽象工厂更注重多个系列的产品对象,而Builder模式则着重于一步一步的构建一个复杂的对象,在最后一步才返回产品,

    使用建造者模式的好处是:

    1.将构造代码和表示代码相分离;

    2.可以改变产品内部的表达方式

    <?php
    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=array(
      "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
    {
      var$_config=null;
      var$_object=null;
    
      public function ProductBuilder($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();
    

      

  • 相关阅读:
    Mac 10.13安装telnet
    如何用万用表判断一个12V蓄电池是否没电
    CentOS 7开机不执行/etc/rc.local的解决方法
    华为S5300系列交换机限制特定IP可以登录Web
    Java Bean Validation 最佳实践
    一文说清文本编码那些事
    定义物料组(Material Group)
    kibana 搜索语法
    微服务相关
    Solve Error: nafxcw.lib(afxmem.obj) : error LNK2005: "void * __cdecl operator new[](unsigned int)" (??_U@YAPAXI@Z) already defined in libcpmt.lib(newaop.obj)
  • 原文地址:https://www.cnblogs.com/EvanHe/p/5473525.html
Copyright © 2011-2022 走看看