Builder mode: abstracts the construction process of complex objects so that different implementation methods of this abstract process can construct objects with different attributes. When constructing an object, the constructed process is the same, but the specific operations corresponding to each step are different. In this case, you can fix the initialization to a virtual function to an abstract base class. This abstract base class is called the abstract builder class; the specific implementation is defined by the virtual function that is rewritten in the derived class. This derived class is called the specific builder class. With specific construction steps, the next step is to call these steps in sequence, which is managed by a class called the conductor. The following uses a C ++ program to simulate the builder mode.
# Include <iostream> # include <string> using namespace STD; // product class PC {public: // print the configuration void display () {cout <"CPU: "<CPU <Endl; cout <" memory: "<memory <Endl; cout <" harddisk: "
Running result:
All the steps for assembling a PC are included in the abstract base class pcbuilder, which only contains some interfaces. The specific implementation is defined in the derived class. Concretebuilder1 and concretebuilder2 represent two types of configurations respectively, so their overwrites to virtual functions are different. Note that the builder class contains the object to be constructed. This object is called product. With different configurations, we need to define a conductor class to arrange the PC assembly process. In this example, the conductor class is ctor. When the user code uses the conductor class to assemble the prepared configuration, it assembles the configuration strictly according to the steps in the Director object. The Assembly details are transparent to the user. The builder mode is mainly used to create complex objects. The construction sequence of these objects is usually stable, but the internal representation is different. Encapsulates complex constructor operations in a class so that when you instantiate an object, the construction will not be incomplete due to missing steps.
Refer:
Chapter 2 of "big talk Design Model"