Creator mode:
In the creator mode, the client is no longer responsible for the creation and assembly of the object, but rather the responsibility for creating the object is given to its specific creator class, the responsibility of the Assembly to the Assembly class, the client pays the call to the object, thus clarifying the responsibilities of each class.
Scenario: Create a very complex, step-by-step assembly.
Copy Code code as follows:
<?php
/**
* Creator mode
*/
Shopping Cart
Class ShoppingCart {
Selected items
Private $_goods = Array ();
Coupons to use
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));
}
}
If we want to restore something to a shopping cart, such as when the user closes the browser and then opens it, it is restored according to the cookie
$data = Array (
' Goods ' => array (' clothes ', ' shoes '),
' Tickets ' => array (' minus 10 '),
);
If you do not use the Creator mode, you need to restore the shopping cart in the business class step by step
$cart = new ShoppingCart ();
foreach ($data [' goods '] as $goods) {
$cart->addgoods ($goods);
// }
foreach ($data [' tickets '] as $ticket) {
$cart->addticket ($ticket);
// }
$cart->printinfo ();
Exit
We provide the creator class to encapsulate the data assembly of the shopping Cart
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 ();
?>
As can be seen, the external interface will be very simple and standard after encapsulating the data assembly process with the creator-mode objects that are complex to the internal data, and the addition of new data items will not affect the outside.