zoukankan      html  css  js  c++  java
  • php设计模式之建造者模式

    建造者模式

    建造者设计模式的目的是消除其他对象的复杂创建过程。使用建造者设计模式不仅是最佳的做法,而且在摸个对象的构造和配置方法改变时候,可以尽可能的减少重复更改代码。

    <?php
    /**
     *productBuilder.php
     */
    class product
    {
        protected $_type = '';
        protected $_size = '';
        protected $_color = '';
    
        public function setType($type){
            $this->_type = $type;
        }
    
        public function setSize($size){
            $this->_size = $size;
        }
    
        public function setColor($color){
            $this->_color = $color;
        }
    }
    
    /**
     * 创建完整产品的需要将每个配置分别传递给产品类的方法
     */
    $productConfigs = array('type'=>'shirt', 'size'=>'XL', 'color'='red');
    
    $product = new product();
    $product->setType($productConfigs['type']);
    $product->setSize($productConfigs['size']);
    $product->setColor($productConfigs['color']);
    /**
     * 当product类发生改变时候,比如增加或者减少配置项,需要在所有实例化的地方更改代码。
     */
    
    /**
     * productBuilder 不仅存储配置参数,而且存储一个实例化的新product实例。
     */
    class productBuilder
    {
        protected $_product = NULL;
        protected $_configs = array();
    
        public function __construct($configs){
            $this->_product = new product();
            $this->_xml = $configs;
        }
    
        public function build(){
            $this->_product->setSize($configs['size']);
            $this->_product->setType($configs['type']);
            $this->_product->setColor($configs['color']);
        }
    
        public function getProduct(){
            return $this->_product;
        }
    }
    
    $builder = new productBuilder($productConfigs);
    $builder->build();
    $product = $builder->getProduct();
  • 相关阅读:
    Windows Bat命令常用操作
    Centos下安装Geth
    Centos常用操作
    为什么CEdit使用SetSel无法取消选择?
    VC编译参数/Zm问题
    XX.exe已经停止工作,的处理兼容性
    excel表,Alt+F11调用出vb语言处理excel表内容,很方便
    在限制了可选日期范围的calendar中,使几个日期不可选的方法
    Agile敏捷开发
    做软件的这些年
  • 原文地址:https://www.cnblogs.com/happig/p/5365884.html
Copyright © 2011-2022 走看看