一个更加简洁的 建造者模式

本文通过一个具体的PHP示例介绍了建造者模式的基本概念及其应用。建造者模式能够将复杂对象的构造与其表示分离,使得相同的构建过程可以创建不同的表示。文中还对比了使用与不使用建造者模式时产品的创建过程。
<?php
/**
 * 建造者模式
 * 将一个复杂对象的构造与它的表示分离,是同样的构建过程可以创建不同的表示;
 * 目的是为了消除其他对象复杂的创建过程
 */

/**
 * 产品,包含产品类型、价钱、颜色属性
 */
class Product
{
    public $_type  = null;
    public $_price = null;
    public $_color = null;
    //建造产品的类型
    public function setType($type)
    {
        echo 'set the type of the product,';
        $this->_type = $type;
    }
    //建造产品的价格
    public function setPrice($price)
    {
        echo 'set the price of the product,';
        $this->_price = $price;
    }
    //建造产品的颜色
    public function setColor($color)
    {
        echo 'set the color of the product,';
        $this->_color = $color;
    }
}

/*将要建造的,目标对象的参数*/
$config = array
(
    'type'  => 'shirt',
    'price' => 100,
    'color' => 'red',
);

/*不使用建造者模式*/
$product = new Product();
$product->setType($config['type']);
$product->setPrice($config['price']);
$product->setColor($config['color']);
//var_dump($product);


/**
 * builder类--使用建造者模式
 */
class ProductBuilder
{
    public $_config = null;
    public $_object = null;

    public function ProductBuilder($config)
    {
        $this->_object = new Product();//在这里借用具体生产过程的对象
        $this->_config = $config;
    }

    public function build()
    {
        echo '建造类开始工作了:';
        $this->_object->setType($this->_config['type']);
        $this->_object->setPrice($this->_config['price']);
        $this->_object->setColor($this->_config['color']);
    }

    public function getProduct()
    {
        return $this->_object;
    }
}

$objBuilder = new ProductBuilder($config);//新建一个建造者
$objBuilder->build();//建造者去建造
$objProduct = $objBuilder->getProduct();//建造者返回-它建造的东西

var_dump($objProduct);


?>

 

转载于:https://www.cnblogs.com/jiufen/p/4994604.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值