• 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();
  • 相关阅读:
    vba create rectangle 矩形
    (zz)nnotation学习笔记2:关于Annotation与符号,还是要读arcmap帮助!!!
    backgroundworker
    C# , mongodb ,study
    工作中常用的dos命令 数据处理经验总结
    你需要明白的SQL SERVER书签查找(Bookmark Lookup)
    使用CalendarExtender
    js控制5秒后页面自动跳转
    HTML按秒数的页面跳转
    序列化与反序列化读取保存xml文件
  • 原文地址:https://www.cnblogs.com/happig/p/5365884.html
Copyright © 2020-2023  润新知