The Builder Pattern uses multiple simple objects to build a complex object step by step. This type of design pattern is the creation pattern, which provides the best way to create objects.
A Builder class constructs the final object step by step. The Builder class is independent of other objects.
, for example, a computer is made up of OPU, motherboard, memory, hard disk, video card, chassis, monitor, keyboard, mouse and other components are assembled, the buyer is not possible to assemble a computer, but computer configuration requirements told computer sales company, computer sales company to arrange technicians to assemble the computer, and then to the buyer to buy the computer.
There are many such examples in life. For example, different characters in the game are different in gender, personality, ability, face shape, body shape, clothing, hair style and other characteristics. There are also a variety of steering wheel, engine, frame, tire and other parts in the car; The sender, recipient, subject, content, attachment and other contents of each email are also different.
All of these products are made up of multiple parts that can be selected flexibly, but the steps to create them are pretty much the same. The creation of such products cannot be described by the factory pattern described earlier, and only the Builder pattern can describe the creation of such products well.
2.1 Modal Motivation
Whether in the real world or in software systems, there are complex objects that have multiple components, such as cars, which include wheels, steering wheels, transmitters, and other components. For most users, the assembling of the parts of a don’t need to know these details, also almost don’t use a single component, but use, is a complete car, can pass the builder pattern to design and the description, the builder pattern can separate parts and the assembly process, step by step to create a complex object. Users only need to specify the type of a complex object to get it, without knowing the details of its construction.
In software development, there are also a large number of complex objects like cars that have a set of member attributes, some of which are reference type member objects. And in these complex objects, there may be some restrictions, such as some attributes are not assigned value complex objects can not be used as a complete product; Some attributes must be assigned in a certain order, one attribute may not be assigned before another, and so on.
A complex object is the equivalent of a car to be built, the properties of an object are the parts of the car, and the process of building a product is the process of assembling parts. Due to the process of composite parts is very complex, so the combination of these parts process is often called “externalizing” to a builder object, builders returned to the client object is a complete product is built, and the user does not need to care about this object contains attributes and their way of assembly, this is the motivation of the builders mode.
2.2 Definition and characteristics of the mode
Builder Pattern: Separates the construction of a complex object from its representation so that the same construction process can create different representations.
The Builder pattern, which creates a complex object step by step, allows users to build complex objects simply by specifying their type and content, without needing to know the specific build details inside. The Builder pattern belongs to the object creation pattern. Depending on the Chinese translation, builder mode can also be called generator mode.
The main advantages of this mode are as follows:
1. Each specific builder is independent of each other, which facilitates the expansion of the system. 2. The client does not need to know the details of the internal composition of the product, so as to control the detailed risks.
Its disadvantages are as follows:
1. The components of the product must be the same, which limits its scope of use. 2. If the internal changes of the product are complex, this pattern can add a lot of builder classes.
The Builder pattern and the factory pattern have different concerns: the Builder pattern focuses on the assembly process of parts, while the factory method pattern focuses on the creation process of parts, but the two can be used together.
2.3 Structure and implementation of the mode
Builder mode is composed of four elements: product, abstract Builder, concrete Builder and commander. Now we analyze its basic structure and implementation method.
2.3.1 Pattern structure
The main roles of Builder mode are as follows.
A Product role (Product) : A complex object consists of several components, whose components are created by a specific builder. Anyway abstract Builder: It is an interface that contains an abstract method for creating the various child parts of a product, usually including a method getResult() that returns a complex product. A Concrete Builder, which implements the Builder interface to build components of a complex product. A conductor (Director) : It calls the component construction and assembly methods in the builder object to create a complex object, without involving the specific product information in the conductor.
Its structure is shown in Figure 1.
Figure 1 Structure of the Builder pattern
The Builder defines the interface to create the parts of a Product. ConcreteBuilder in the concrete implementation of each part of the creation of the Product interface, is the concrete builders. Director builds the Product according to the needs of users (how to build the specific Product, how to build the various parts of the Product). This pattern is used to create complex objects that are built in a stable order, but are often subject to complex changes.
2.3.2 implementation of pattern (C++ implementation)
So how does the Builder pattern work? For example, different ConcreteBuilder classes can be implemented in different ways. In this way, the template method pattern (described in a later section) is applied similarly to the builder pattern. However, the focus of the Builder pattern is that different directors can be presented differently, while the focus of the template method pattern is the different implementation of each step in the algorithm. In addition, the relationships between their classes are different. The template approach is implemented by inheritance, while the builder pattern is implemented by composition. The template method pattern is mainly used to execute different algorithms, and the Builder pattern is mainly used to build objects. However, both modes can achieve many similar functions. That’s okay, there are multiple ways to implement the same functionality. It depends on demand. In addition, in the actual writing of the program, there is no need to stick to a certain design mode, as long as the relevant principles, so that the whole program is efficient, stable, easy to expand, easy to maintain. There are also differences in the scenarios used.
The code looks like this:
#include <iostream>
#include <vector>
using namespace std;
/ / product
class Product
{
public:
void Add(string str)
{
m_vec.push_back(str);
}
void Show(a)
{
for (auto it = m_vec.cbegin(a); it ! = m_vec.cend(); it++)
{
cout << *it << endl;
}
}
private:
vector<string> m_vec;
};
// Constructor class
class Builder
{
public:
virtual void BuildPartA(a) = 0;
virtual void BuildPartB(a) = 0;
virtual void BuildPartC(a) = 0;
virtual Product getResult(a) = 0;
};
class ConcreteBuilder_0 : public Builder
{
public:
ConcreteBuilder_0() : m_p(nullptr)
{
m_p = new Product(a); }virtual ~ConcreteBuilder_0()
{
if (nullptr == m_p)
delete m_p;
}
virtual void BuildPartA(a)
{
string str = "Builder_0 BuildPartA";
m_p->Add(str);
}
virtual void BuildPartB(a)
{
string str = "Builder_0 BuildPartB";
m_p->Add(str);
}
virtual void BuildPartC(a)
{
string str = "Builder_0 BuildPartC";
m_p->Add(str);
}
Product getResult(a)
{
return *m_p;
}
private:
Product * m_p;
};
class ConcreteBuilder_1 : public Builder
{
public:
ConcreteBuilder_1() : m_p(nullptr)
{
m_p = new Product(a); }virtual ~ConcreteBuilder_1()
{
if (nullptr == m_p)
delete m_p;
}
virtual void BuildPartA(a)
{
string str = "Builder_1 BuildPartA";
m_p->Add(str);
}
virtual void BuildPartB(a)
{
string str = "Builder_1 BuildPartB";
m_p->Add(str);
}
virtual void BuildPartC(a)
{
string str = "Builder_1 BuildPartC";
m_p->Add(str);
}
Product getResult(a)
{
return *m_p;
}
private:
Product * m_p;
};
// Commander class
class Director
{
public:
// How is this implemented according to the requirements
void build(Builder *p)
{
p->BuildPartA(a); p->BuildPartC(a); p->BuildPartB();
}
};
int main(int argc, char *argv[])
{
// Dynamic association, dynamic association
// Builder mode
Builder *builder= new ConcreteBuilder_0(a); Director * director =new Director(a); director->build(builder);
builder->getResult().Show(a); builder =new ConcreteBuilder_1(a); director->build(builder);
builder->getResult().Show(a);if(director ! =NULL)
{
delete director;
director = NULL;
}
if(builder ! =NULL)
{
delete builder;
builder= NULL;
}
return 0;
}
Copy the code
2.4 Application Scenarios of Mode
The Builder pattern can be used when:
A product object needs to be generated, which typically has multiple member attributes, to have a complex internal structure. The attributes of a product object to be generated depend on each other, and the order in which they are generated is specified. A virtual object is created independently of the class that creates it. The director class was introduced in the Builder pattern, encapsulating the creation process in the director class instead of the Builder class. Queues isolate the creation and use of complex objects, and allow the same creation process to create different products.
In many game software, the map includes sky, ground, background and other components, and the character includes human body, clothing, equipment and other components. The builder mode can be used to design it, and different types of maps or characters can be created by different specific builders.
2.5 Schema extensions
Simplification of the Builder model:
Regardless of the abstract builder: You can omit the abstract builder if only one concrete builder is needed in the system. Forgetting the role of commander: When there is only one Builder, the role of commander can be omitted if the abstract Builder role has already been omitted, allowing the Builder role to play both the role of commander and Builder.
Builder pattern vs. Abstract Factory pattern:
In contrast to the Abstract factory model, the Builder model returns an assembled complete product, while the Abstract factory model returns a series of related products that sit in different product hierarchies, forming a product family. in the abstract factory pattern, the client class instance chemical plant, and then call the factory method to obtain the required product object, in the builder pattern, the client can not directly call the builders of relevant methods, but by commanders class to guide how to generate object, including the object of assembly process and construction step, step by step, it focuses on the construction of a complex object, Returns a complete object. At the same time, the builder mode is a car assembly factory, which returns a complete car by assembling parts.
2.6 summarize
A complex object is composed of several parts. The Builder pattern separates the creation of complex objects from the creation of parts, represented by the Builder class and the Director class respectively. The Director builds the final complex object, and what is encapsulated in the Builder interface above is how to create the parts that make up the complex object, that is, how the Director is responsible for the final assembly of the parts into the product. In this way, the builder pattern decouples the design and implementation.
When first introduced to the Builder pattern, it is easy to confuse the Builder with the abstract factory pattern. Due to which belong to the creational design patterns, so there are common point between the two, but the builder pattern to focus on objects combination, namely different small object form an integral part of the complex large objects, and the abstract factory pattern for interface programming, just provide factory interface for creating an object, object is not responsible for after processing.
The Builder pattern is a complex design pattern that is not easy to balance. You should read more open source code to understand how others are using the pattern. Learn design patterns from practical applications.