建造者模式

建造者模式

作者:LAMP小白  点击:1680  发布日期:2012-10-05 20:32:00  返回列表
如果我们正在使用一个老版本的类,但是突然这个类换成了新的版本,我们怎么解决呢?
哈哈,可以使用建造者模式

所谓建造者模式其实适配器模式比较类似,不同的是,适配器模式在换了新版本之后,我们只是用一个新的类去继承老版本从而继续使用老版本的功能,但建造者模式是在设计之初就为一个不稳定的类(姑且就这么说吧),建立一个中间类,这个中间类负责整理实例化类所需要的数据并返回我们希望的数据
这样做的好处是,我们不用再去修改实际文件中的代码了,只需要修改中间类的代码即可完成类版本的交替...但坏处是,我们没办法像适配器模式那样保留老版本的功能了,目标类的全部代码都被换成新的了


比如这是一个老版本类和中间类
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;
    }
}
object = new protected();
            $this->config = $config;
        }
        public function init()
        {
            $this->object->setType($this->config['type']);
            $this->object->setSize($this->config['size']);
            $this->object->setColor($this->config['color']);
            return $this->object;
        }
    }
?>

这是新的版本,我们只需要简单修改中间类即可完成更新

class builder
{
    protected $object;
    public function __construct($config)
    {
        $this->object = new protected($config);
    }
    public function init()
    {
        return $this->object;
    }
}


上一篇:适配器模式 下一篇:快递查询API
0