Creator mode:
In the creator mode, the client is no longer responsible for the creation and assembly of objects, but rather the responsibility of creating the object to its specific creator class, the Assembly of responsibility to the Assembly class, the client pays the call to the object, thus clarifying the responsibilities of each class.
Scenario: Creation is very complex and is assembled in steps.
Copy CodeThe code is as follows:
<?php
/**
* Creator mode
*/
Shopping Cart
Class ShoppingCart {
The selected item
Private $_goods = Array ();
Coupon for 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 from the shopping cart, such as when the user closes the browser and then opens it, it will be restored according to the cookie
$data = Array (
' Goods ' = = Array (' clothes ', ' shoes '),
' Tickets ' = = Array (' minus 10 '),
);
If you do not use Creator mode, you will need to restore your 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 you can see, using the creator pattern to encapsulate the data assembly process for objects with complex internal data, the external interface is very simple and prescriptive, and adding new data items without any external impact.