Design Pattern (3) Builder model Builder (http://blog.csdn.net/hguisu/article/details/7518060) 1. Overview
In the process of software development, when a "complex object" is created, this object is composed of sub-objects of certain parts using a certain algorithm. due to changes in requirements, various parts of complex objects often face drastic changes, but the algorithms that combine them are relatively stable.
Example 1:Buy KFC
A typical children's meal includes a staple food, a complementary food, a drink, and a toy (such as a hamburger, fried chicken, cola, and toy car ). These can be different in different children's meals, but the process of combining them into children's meals is the same.
Client: customers who want to buy a set of packages (including hamburgers, cola and french fries) can choose between 1 and 2.
Instructor role: cashier. Know what kind of package the customer wants to buy and tell the restaurant staff to prepare the package.
Builder role: restaurant staff. Prepare the specific package according to the cashier's requirements, and put the package into the hamburger, cola, and fries respectively.
Product role: the final package. Everything is placed on the same plate.
Example 2: Calculate the salary:The salary is generally calculated as follows: base salary + bonus-tax. However, the base salary is divided into three levels: Level 1 8000, level 2 6000, and level 3 4000. Based on different positions, different bonuses are issued. Management and daily transaction processing positions (Class A) Calculate bonuses and sales positions (Class B) based on the evaluation scores of leaders and colleagues each month) the Commission is based on the sales amount. The tax amount is calculated based on the amount of bonus and base salary. From this we can see that the calculation method of this salary is relatively stable, but each part of the salary will generate different algorithms according to different situations, how to separate the client from the ever-changing base salary, bonus, and tax calculation methods is also suitable for the builder mode.
2. Problem
How can we cope with such changes and provide an "encapsulation mechanism" to isolate the changes of "various parts of complex objects, so as to keep the "stable algorithm Construction" in the system and not change with the demand?
3. Solution
Builder mode: separates the construction of a complex object from its representation, so that different representations can be created during the same build process.
4. Applicability
Use the Builder mode in the following cases
• When creating complex objects, algorithms should be independent of the components of the objects and their assembly methods.
• When the constructor must allow different representations of the constructed object.
5. Structure
The structure of this mode is shown in the next page.
6. Composition of the build Mode
• Abstract builder role(Builder): specify an abstract interface for each part of a Product object to standardize the construction of each component of the Product object. Generally, this role specifies which parts of a complex object are created and does not involve the creation of specific object parts.
•Specific Builder(ConcreteBuilder)
1) Implement the Builder interface to construct and assemble each part of the product. ImplementationAbstract Builder role Builder.
2) Define and define the representation it creates, that is, the creation of various parts of a complex object based on different business logic
3) provides an interface for retrieving Products
4) construct an object using the Builder interface, that is, create a product instance by calling the instructor.
Instructor(Director): Call a specific builder role to create parts of a product object. The instructor does not have information about specific products. The information about specific products is the object of specific builders. It is only responsible for ensuring that all parts of the object are completely created or created in a certain order.
Product role(Product): complex objects under construction. It includes the classes that define components, including the interfaces that assemble these components into products.
7. Effect
Main Effects of the builder mode:
1) it allows you to change the internal representation of a product. The Builder object is provided to the Guide to construct an abstract interface for the product. This interface allows the generator to hide the representation and internal structure of this product. It also hides how the product is assembled. Because the product is constructed through abstract interfaces, all you need to do when changing the internal representation of the product is to define a new generator.
2) It separates the constructor code from the representation code. In builder mode, the constructor encapsulates the creation and representation of a complex object to improve the modularity of the object. The customer does not need to know all information about the classes that define the internal structure of the product. These classes are not found in the builder interface. Each concrete
Builder contains all the code for creating and assembling a specific product. The Code only needs to be written once. Different ctor can reuse it to construct different products based on the same part set.
3) it allows you to more precisely control the construction process. The Builder mode is different from the Creation Mode of the product generated at once. It constructs the product step by step under the control of the Guide. The Guide retrieves the product from the generator only when the product is completed. Therefore, the builder interface can better reflect the product construction process than other creation modes. This allows you to control the building process more precisely, so that you can control the internal structure of the resulting product more precisely.
8. Implementation: Instructor: Cashier
<? PHP/*** INSTRUCTOR: cashier **/class directorcashier {/*** food returned by cashier restaurant staff **/Public Function buildfood (builder $ builder) {$ builder-> buildpart1 (); $ builder-> buildpart2 ();}}
Abstract builder:
/*** Abstract builder **/abstract class builder {/*** create the first part of the product */public abstract function buildpart1 (); /***** create the second part of the product */public abstract function buildpart2 ();/***** return product */public abstract function getproduct ();}
Specific builder class:
/*** Specific Builder class: restaurant staff, the returned package is: Hamburger two + Drink one **/class ConcreteBuilder1 extends Builder {protected $ _ product = null; // product object function _ construct () {$ this-> _ Product = new product ();}/*** create the first part of the Product :: hamburg = 2 */public function buildPart1 () {$ this-> _ product-> add ('hamburger ', 2);}/*** create the second part of the product: */public function buildPart2 () {$ this-> _ product-> add ('Drink ', 1);}/*** return the product object: **/public function getProduct () {return $ this-> _ product ;}}/*** specific builder class: restaurant staff, 1 hamburger + 2 drinks **/class ConcreteBuilder2 extends Builder {protected $ _ product = null; // product object function _ construct () {$ this-> _ product = new Product ();}/*** create the first part of the product: Hamburg */public function buildPart1 () {$ this-> _ product-> add ('hamburger ', 1);}/*** create product part 2: drink = 2 */public function buildPart2 () {$ this-> _ product-> add ('Drink ', 2);}/*** return product object: **/public function getProduct () {return $ this-> _ product ;}}
Product Type:
/*** Product class */class Product {public $ products = array ();/*** add a specific Product */public function add ($ name, $ value) {$ this-> products [$ name] = $ value;}/*** view the product for the customer */public function showToClient () {foreach ($ this-> products as $ key = >$ v) {echo $ key, '=', $ v, '<br> ';}}}
Customer program:
// Customer program class Client {/*** customer purchase package **/public function buy ($ type) {// instructor, cashier $ ctor = new DirectorCashier (); // restaurant staff, cashier $ class = new ReflectionClass ('concretebuilder '. $ type); $ concreteBuilder = $ class-> newInstanceArgs (); // The cashier combines the food returned by an employee $ director-> buildFood ($ concreteBuilder ); // return $ concreteBuilder-> getProduct ()-> showToClient () ;}/// test ini_set ('display _ errors ', 'on '); $ c = new Client (); $ c-> buy (1); // purchase Package 1 $ c-> buy (2); // purchase Package 19. Advantages of the builder ModeFirst, the builder mode is well encapsulated. The builder mode can effectively encapsulate changes. In the scenario where the builder mode is used, the product class and the builder class are relatively stable. Therefore, encapsulating the main business logic in the director class can achieve better stability on the whole.
Second, the builder mode is easy to expand. If you have new requirements, you can implement a new builder class. Basically, you do not need to modify the code that has been tested before, so there is no risk to the original function.
10. Differences between builder and factory modelsWe can see that the builder model is very similar to the factory model. In general, the builder model only has one "director" role more than the factory model. In the class diagram of the builder mode, if the director class is regarded as the client for the final call, the rest of the diagram can be regarded as a simple factory model.
The builder mode is generally used to createMore complex objectsBecause the object creation process is more complex, the object creation process is independent to form a new class-the director class. In other words, the factory mode encapsulates all the object creation processes in the factory class, and the factory class provides the final product to the client. In the builder mode, the builder class generally only provides the construction of each component in the product class, and delivers the specific construction process to the director class. The Director is responsible for forming various components into products according to specific rules, and then delivering the group-created products to the client.
11. ConclusionThe builder mode is similar to the factory mode. They are both the builder mode and the applicable scenarios are similar. Generally, if the product is builtComplicated, Use the factory model; if the product is builtMore complex, Use the builder mode.