I understand the design pattern (C ++ implementation) -- builder Pattern)

Source: Internet
Author: User
Solved problems:

The object I created is complex, and the member functions in the object use different implementations to represent different instances. In other words, the same object construction process can have different representations. For example, when I went to eat rice noodles over the bridge that day, they had different packages. The packages included the same types, including a bowl of rice noodles, a cold dish, and a drink. However, none of the three packages are the same. Now we can use the builder mode.


Class chart structure:


1. Builder role: provides an abstract interface to standardize the construction of each component of a product object. Generally, this interface is independent from the business logic of the application. In this mode, the specific builder role is directly created for the product object. The method required by the specific builder class to implement this interface: one is the construction method, and the other is the result return method. At this time, the staff of the rice noodle store prepare a specific package according to the cashier's requirements, and place appropriate rice noodles, cold dishes and drinks.

2. The specific builder role: this role is played by closely related classes of the application. They create product instances under application calls. The main tasks completed by this role include implementing the interfaces provided by the builder role and completing the process of creating a product instance step by step. After the construction process is complete, provide the product instance. Is the employee who makes a specific package.

3. ctor role: the class that acts as the role calls the specific builder role to create product objects. The director does not have the specific knowledge of the product class. What really possesses the specific knowledge of the product class is the specific builder object. The cashier knows what package I want. He will tell the staff in the MI store what package I want to prepare.

4. Product role: a product is a complex object during construction. The mentor role is a role that deals with clients. The Director role divides the client product creation request into the construction request for each part, and then delegates these requests to the specific builder role. The specific builder role is used for specific construction, but is not known to the client. Is the final package, and everything is put together.


Example:

// CplusplusBuild.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <vector>#include <string>#include <iostream>using namespace std;//productclass Food{private:vector<string> mFoodName;vector<int> mFoodPrice;public:void add(string foodName,int price){mFoodName.push_back(foodName);mFoodPrice.push_back(price);}void show(){cout<<"Food List" <<endl;cout<<"-------------------"<<endl;for(int i=0;i<mFoodName.size();i++){cout<<mFoodName[i]<<" "<<mFoodPrice[i]<<endl;}}};//builderclass Builder{public:virtual void BuildRiceNoodles() {};virtual void BuildCoolDish(){};virtual void BuildDrink(){};virtual Food * getFood(){return NULL;}};//builderAclass BuilderA:public Builder{private:Food *food;public:BuilderA(){food = new Food();}void BuildRiceNoodles(){food->add("RiceNoodlesA",20);}void BuildCoolDish(){food->add("CoolDishA",20);}void BuildDrink(){food->add("DrinkA",20);}Food * getFood(){return food;}};//builderBclass BuilderB:public Builder{private:Food *food;public:BuilderB(){food = new Food();}void BuildRiceNoodles(){food->add("RiceNoodlesB",10);}void BuildCoolDish(){food->add("CoolDishB",10);}void BuildDrink(){food->add("DrinkB",10);}Food * getFood(){return food;}};//directorclass FoodManager{public:void Construct(Builder * builder){builder->BuildRiceNoodles();builder->BuildDrink();builder->BuildCoolDish();}};//clentint _tmain(int argc, _TCHAR* argv[]){FoodManager *foodManager= new FoodManager();Builder * builder = new Builder();// the following code can use simple factory;char ch;cout<<"input your food Type (A or B):";cin>>ch;if(ch=='A'){builder = new BuilderA();}else if(ch=='B'){builder = new BuilderB();}foodManager->Construct(builder);Food * food = builder->getFood();food->show();return 0;}

Expansion of builder mode:

The builder mode can evolve into multiple forms during use:

Omitting the abstract builder role

If you only need a specific builder in the system, you can omit the abstract builder. This code may be as follows:

 

//directorclass FoodManager{private:BuilderA * builder;public:FoodManager() {builder = new BuilderA();};void Construct(){builder->BuildRiceNoodles();builder->BuildDrink();builder->BuildCoolDish();}};

The instructor role is omitted.

If there is only one specific builder, if the abstract builder role has been omitted, you can also omit the mentor role and let the builder assume the dual role of the mentor and builder. This code may be as follows:

//builderclass Builder{private:Food * food;public: Builder(){food = new Food();} void BuildRiceNoodles() {//..}; void BuildCoolDish(){//..}; void BuildDrink(){//..}; Food * getFood(){return food;} void Construct() { BuildRiceNoodles(); BuildCoolDish(); BuildDrink(); }};

At the same time, the client also needs to make corresponding adjustments, as shown below:

//clientint _tmain(int argc, _TCHAR* argv[]){Builder * builder = new Builder();    builder->Construct();Food *food = builder->getFood();food->show();return 0;}

Stringbuilder in C # is an example.

Implementation points:

1. The Builder mode is mainly used to "build a complex object by step", where "each step" is a stable algorithm, and the steps of complex objects change frequently.

2. the abstract factory model mentioned in the previous article solves the changes in the demand for "series objects", while the builder model solves the changes in the "Object part" of a single object.

Abstract classes are not required for products, especially when the algorithm used to create objects is complex, or 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 for creating 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, but this is not absolute, in particular, text conversion is similar. In this case, the default method is a reasonable default operation to export the input that remains unchanged.

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.

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 the build code from the implementation 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.


Lcl_data was originally created in csdn. Net [http://blog.csdn.net/lcl_data/article/details/8758477]


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.