This article uses examples to show us the Creator mode in the php design mode and the scenario in which the Creator mode is applied. We recommend it to you here.
This article uses examples to show us the Creator mode in the php design mode and the scenario in which the Creator mode is applied. We recommend it to you here.
Creator mode:
In the Creator mode, the client is no longer responsible for object creation and assembly. Instead, it submits the responsibility for object creation to its specific creator class and the Assembly responsibility to the Assembly class, the client calls the object to clarify the responsibilities of each class.
Application Scenario: the creation process is complex and assembled in steps.
The 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 the shopping cart, for example, when the user closes the browser and then opens it, it will be restored Based on the cookie.
$ Data = array (
'Goods' => array ('clothes ', 'shoes '),
'Tickets '=> array ('subtract 10 '),
);
// If the Creator mode is not used, you need to restore the shopping cart step by step in the business class.
// $ 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 ();
?>
It can be seen that the external interface will be very simple and standardized after the data assembly process is encapsulated for complex internal data objects in the Creator mode, and adding and modifying new data items will not affect the external environment.
,