Builder pattern (converted from terrylee)

Source: Internet
Author: User

Overview 

In a software system, sometimes it is faced with the creation of "a complex object", which is usually composed of sub-objects of each part using a certain algorithm; due to changes in requirements, the various parts of this complex object often face drastic changes, but the algorithms that combine them are relatively stable. How to deal with this change? How can we provide a "encapsulation mechanism" to isolate the changes of "various parts of complex objects", so as to keep the "stable Construction Algorithm" in the system from changing with demand? This is the builder mode.

This article explains the builder mode through examples of purchasing KFC in real life.

Intention 

Separates a complex build from its representation so that different representations can be created during the same build process.

Model Diagram 

 

Examples in life 

The builder mode separates the construction of complex objects from the presentation of objects, so that the same building process can create different representations. This mode is used to make children's meals in fast food restaurants. 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. The process is the same no matter whether the customer orders a hamburger, sanmingzhi or chicken. The staff at the counter directly put the staple food, complementary food and toys together. These are put in a bag. The drink is poured into the cup and placed outside the bag. These processes are the same in competing restaurants.

 

Implementation Process Diagram 

Here we take the KFC store as an example to buy a package, as shown below:

 

Client: customer. If you want to buy a set of packages (including hamburgers, cola, and Fries), you 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.

Next we will start the package purchase process.

1. The customer creates a derector object and configures it with the builder object it wants. When a customer enters the KFC store and wants to buy a package, he first finds a cashier, which is equivalent to creating a mentor object. The cashier provides two packages for customers: 1 standard package and 2 gold package. The finished work is shown in red in the sequence chart.

Product (Package) category:

 

Code

1 using system;
2 using system. Collections. Generic;
3 using system. LINQ;
4 using system. text;
5 using system. collections;
6
7 namespace builderdemo
8 {
9 /// <summary>
10 // food class, both product class
11 /// </Summary>
12 public class food
13 {
14 hashtable food = new hashtable ();
15
16 /// <summary>
17 // Add food
18 /// </Summary>
19 /// <Param name = "strname"> food name </param>
20 /// <Param name = "price"> price </param>
21 public void add (string strname, string price)
22 {
23 food. Add (strname, price );
24}
25
26 /// <summary>
27 // display the food list
28 /// </Summary>
29 public void show ()
30 {
31 idictionaryenumerator myenumerator = food. getenumerator ();
32 console. writeline ("food list :");
33 console. writeline ("------------------------------");
34 string strfoodlist = "";
35 while (myenumerator. movenext ())
36 {
37 strfoodlist = strfoodlist + "\ n" + myenumerator. Key. tostring ();
38 strfoodlist = strfoodlist + ": \ t" + myenumerator. value. tostring ();
39}
40 console. writeline (strfoodlist );
41 console. writeline ("\ n ------------------------------");
42}
43}
44
45}
46

2. The instructor notifies the builder. The Cashier (Instructor) informed the restaurant staff to prepare the package. Here we prepare the order of the package: Put the hamburger, cola into the cup, the fries into the box, and put these items on the plate. This process is the same for general and gold packages. The difference is that their prices for hamburgers, cola and fries are different. As shown in the red part of the sequence chart:

 

Code

1 using system;
2 using system. Collections. Generic;
3 using system. LINQ;
4 using system. text;
5
6 namespace builderdemo
7 {
8 /// <summary>
9 // foodmanager class, that is, instructor
10 /// </Summary>
11 class foodmanager
12 {
13 public void construct (Builder)
14 {
15 builder. buildhamb ();
16
17 builder. buildcoke ();
18
19 builder. buildchip ();
20}
21}
22}
23

 

 

3. The Builder handles the instructor's requirements and adds parts to the product. The restaurant staff (builder) Put the corresponding hamburger, cola, and fries on the plate as the cashier requested. This part is a changeable part of the builder model. Because the customer chooses different packages and the package assembly process is different, this step completes the creation of product objects.

Program Implementation:

 

 

Code

1 using system;
2 using system. Collections. Generic;
3 using system. LINQ;
4 using system. text;
5
6 namespace builderdemo
7 {
8 /// <summary>
9 // builder class, that is, abstract builder class, constructing a package
10 /// </Summary>
11 public abstract class Builder
12 {
13 /// <summary>
14 // Add a hamburger
15 /// </Summary>
16 public abstract void buildhamb ();
17
18 /// <summary>
19 // Add cola
20 /// </Summary>
21 public abstract void buildcoke ();
22
23 /// <summary>
24 // Add fries
25 /// </Summary>
26 public abstract void buildchip ();
27
28 /// <summary>
29 // return results
30 /// </Summary>
31 /// <returns> food target </returns>
32 public Abstract Food getfood ();
33}
34
35}
36

 

Code

1 using system;
2 using system. Collections. Generic;
3 using system. LINQ;
4 using system. text;
5
6 namespace builderdemo
7 {
8 /// <summary>
9 // normalbuilder class, specific constructor, general plan
10 /// </Summary>
11 class normalbuilder: Builder
12 {
13 private food normalfood = new food ();
14
15 public override void buildhamb ()
16 {
17 normalfood. Add ("normalhamb", "¥10.50 ");
18}
19
20 public override void buildcoke ()
21 {
22 normalfood. Add ("cokecole", "$4.50 ");
23}
24
25 public override void buildchip ()
26 {
27 normalfood. Add ("firechips", "¥2.00 ");
28}
29
30 public override food getfood ()
31 {
32 return normalfood;
33}
34
35}
36}
37

 

Code

1 using system;
2 using system. Collections. Generic;
3 using system. LINQ;
4 using system. text;
5
6 namespace builderdemo
7 {
8 /// <summary>
9 // goldbuilder class, specific constructor, gold package
10 /// </Summary>
11 class goldbuilder: Builder
12 {
13 private food goldfood = new food ();
14
15 public override void buildhamb ()
16 {
17 goldfood. Add ("goldhamb", "¥13.50 ");
18}
19
20 public override void buildcoke ()
21 {
22 goldfood. Add ("cokecole", "¥4.50 ");
23}
24
25 public override void buildchip ()
26 {
27 goldfood. Add ("firechips", "¥3.50 ");
28}
29
30 public override food getfood ()
31 {
32 return goldfood;
33}
34
35}
36}
37

 

4. The customer retrieves the product from the builder. After preparing the package from the restaurant staff, the customer will get the package back from the restaurant staff. In this step, the customer program only needs to retrieve the generated product objects, as shown in the red section in the time sequence diagram.

Complete customer program:

 

Code

1 using system;
2 using system. Collections. Generic;
3 using system. LINQ;
4 using system. text;
5 using system. reflection;
6 using system. configuration;
7
8 namespace builderdemo
9 {
10 /// <summary>
11 // Client
12 /// </Summary>
13 class Program
14 {
15 static void main (string [] ARGs)
16 {
17 foodmanager = new foodmanager ();
18
19 builder instance;
20
21 console. writeline ("Please enter food no (1-2 ):");
22
23 string NO = console. Readline ();
24
25 string foodtype = configurationsettings. deleettings ["no" + NO];
26
27 // instance = activator. createinstance (type. GetType (foodtype) as builder;
28
29 // instance = new normalbuilder ();
30
31 instance = (builder) Assembly. Load ("builderdemo"). createinstance ("builderdemo." + foodtype );
32
33 foodmanager. Construct (instance );
34
35 Food food = instance. getfood ();
36 food. Show ();
37
38 console. Readline ();
39}
40}
41}
42

The analysis shows that in this example, the plan preparation process is stable, that is, according to certain steps, and the components of the plan are changed, it may be a general package or a gold package. This change is the "change point" in the builder mode, which is the part we want to encapsulate.

 

Implementation points 

1. The Builder mode is mainly used to "build a complex object by step". In this mode, "Step by Step" is a stable algorithm, while each part of a complex object changes frequently.

2. The product does not need abstract classes, especially when this mode is used due to complicated algorithms for creating objects, or when this mode is applied to the product generation process, the final results may vary greatly, it is unlikely to extract an abstract product category.
3. The interface method used to create sub-parts in the Creator is not an abstract method, but an empty method without any operation. The specific creator only needs to override the required method, however, this is not absolute, especially in case of text conversion, the default method is a reasonable default operation to export the input that remains unchanged.

4. the abstract factory model we mentioned above solves the changes in the demand for "series objects" and the builder model solves the changes in the demand for "Object parts, the builder mode is often used in combination with the composite pattern.

Effect 

1. The Builder mode enables independent changes to the internal appearance of the product. By using the builder mode, the client does not have to know the details of the product composition.
2. Each builder is relatively independent of other builders.
3. The construction process can be further controlled.

4. Separate build code from presentation code.

5. The disadvantage of the builder mode is that it is difficult to cope with the changes in the demand for "step-by-step building algorithms.

Applicability 

The builder mode should be used in the following situations:

1. The product objects to be generated have a complex internal structure.
2. The properties of the product objects to be generated are mutually dependent. The Builder mode can force the generation order.
3. Some other objects in the system will be used during object creation. These objects are not easy to obtain during product object creation.

Application scenarios 

1. RTF document exchange format reader.

2. string processing stringbuilder In the. NET environment, which is a simplified builder mode.

3 ,......

Summary

The builder mode decouples the assembly process and creates specific components, so that we do not have to worry about how each component is assembled.

 

Author: terrylee
Source: http://terrylee.cnblogs.com

Builder Pattern)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.