Home  >  Article  >  Backend Development  >  浅析php创建者模式_php实例

浅析php创建者模式_php实例

WBOY
WBOYOriginal
2016-06-07 17:15:19872browse

创建者模式:

在创建者模式中,客户端不再负责对象的创建与组装,而是把这个对象创建的责任交给其具体的创建者类,把组装的责任交给组装类,客户端支付对对象的调用,从而明确了各个类的职责。
应用场景:创建非常复杂,分步骤组装起来。

复制代码 代码如下:

/**
 * 创建者模式
 */
//购物车
class ShoppingCart {
       //选中的商品
    private $_goods = array();
    //使用的优惠券
    private $_tickets = array();
       public function addGoods($goods) {
              $this->_goods[] = $goods;
       }
    public function addTicket($ticket) {
           $this->_tickets[] = $ticket;
    }
    public function printInfo() {
           printf("goods:%s, tickets:%sn", implode(',', $this->_goods), implode(',', $this->_tickets));
    }
}
//假如我们要还原购物车的东西,比如用户关闭浏览器后再打开时会根据cookie还原
$data = array(
       'goods' => array('衣服', '鞋子'),
       'tickets' => array('减10'),
);
//如果不使用创建者模式,则需要业务类里一步步还原购物车
// $cart = new ShoppingCart();
// foreach ($data['goods'] as $goods) {
//   $cart->addGoods($goods);
// }
// foreach ($data['tickets'] as $ticket) {
//   $cart->addTicket($ticket);
// }
// $cart->printInfo();
// exit;
//我们提供创建者类来封装购物车的数据组装
class CardBuilder {
       private $_card;
       function __construct($card) {
              $this->_card = $card;
       }
       function build($data) {
              foreach ($data['goods'] as $goods) {
                     $this->_card->addGoods($goods);
              }
              foreach ($data['tickets'] as $ticket) {
                     $this->_card->addTicket($ticket);
              }
       }
       function getCrad() {
              return $this->_card;
       }
}
$cart = new ShoppingCart();
$builder = new CardBuilder($cart);
$builder->build($data);
echo "after builder:n";
$cart->printInfo();
?>

可以看出,使用创建者模式对内部数据复杂的对象封装数据组装过程后,对外接口就会非常简单和规范,增加修改新数据项也不会对外部造成任何影响。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn