Analyze the php creator mode and analyze the creation of php. Analysis of the php creator mode and the php creator mode: in the creator mode, the client is no longer responsible for object creation and assembly, but is responsible for object creation, analysis on php creation
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.
Creator mode: in the creator mode, the client is no longer responsible for object creation and assembly, but is responsible for object creation...