《PHP編程:淺析php創(chuàng)建者模式》要點:
本文介紹了PHP編程:淺析php創(chuàng)建者模式,希望對您有用。如果有疑問,可以聯(lián)系我們。
PHP教程創(chuàng)建者模式:
PHP教程在創(chuàng)建者模式中,客戶端不再負責對象的創(chuàng)建與組裝,而是把這個對象創(chuàng)建的責任交給其具體的創(chuàng)建者類,把組裝的責任交給組裝類,客戶端支付對對象的調(diào)用,從而明確了各個類的職責.
應用場景:創(chuàng)建非常復雜,分步驟組裝起來.
代碼如下:
<?php
/**
?* 創(chuàng)建者模式
?*/
//購物車
class ShoppingCart {
?????? //選中的商品
??? private $_goods = array();
??? //使用的優(yōu)惠券
??? 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));
??? }
}
//假如我們要還原購物車的東西,好比用戶關閉瀏覽器后再打開時會根據(jù)cookie還原
$data = array(
?????? 'goods' => array('衣服', '鞋子'),
?????? 'tickets' => array('減10'),
);
//如果不使用創(chuàng)建者模式,則需要業(yè)務類里一步步還原購物車
// $cart = new ShoppingCart();
// foreach ($data['goods'] as $goods) {
//?? $cart->addGoods($goods);
// }
// foreach ($data['tickets'] as $ticket) {
//?? $cart->addTicket($ticket);
// }
// $cart->printInfo();
// exit;
//我們提供創(chuàng)建者類來封裝購物車的數(shù)據(jù)組裝
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();
?>
PHP教程可以看出,使用創(chuàng)建者模式對內(nèi)部數(shù)據(jù)復雜的對象封裝數(shù)據(jù)組裝過程后,對外接口就會非常簡單和規(guī)范,增加修改新數(shù)據(jù)項也不會對外部造成任何影響.
《PHP編程:淺析php創(chuàng)建者模式》是否對您有啟發(fā),歡迎查看更多與《PHP編程:淺析php創(chuàng)建者模式》相關教程,學精學透。維易PHP學院為您提供精彩教程。
轉(zhuǎn)載請注明本頁網(wǎng)址:
http://www.snjht.com/jiaocheng/13806.html