In a software system, it is sometimes necessary to create a complex object, and the complex object is composed of a combination of steps by its various molecular objects.
For example, in a procurement system, if a buyer to purchase a batch of computers, in this actual demand, the computer is a complex object, it is CPU, motherboard, hard disk, video card, chassis and other assembled, if at this time to let a buyer a computer to assemble the words are really tired buyers, In this case, we can use the builder model to solve this problem, we can package the computer components of the assembly process into a builder class object, the builder as long as the client is responsible for the return of all components of the finished product object is ready. However, in real life is the case, if the company to buy a batch of computers, the buyer can not buy their own components and organize them, at this time the buyer only need like the computer City boss said he wants to buy what kind of computer can be, computer City boss will naturally assemble a good computer to the company.
One, builder mode
Separating the construction of a complex object from its representation allows the same build process to create different representations.
The builder pattern separates the construction code from the presentation code, which allows the client to avoid knowing the details of the internal composition of the product, thereby reducing the coupling between the client and the specific product.
Ii. class diagram of the builder pattern
Third, the implementation of the builders ' pattern
In this example, the owner of the computer city is directly connected with the customer (that is, the buyer), but the computer is assembled by the boss to command the installation personnel to assemble the various parts of the computer, really responsible for creating products (here the product refers to the computer) is the computer city installed personnel. After clearing up this logical process, here's a concrete look at how to represent this real-life logical process in code:
usingSystem;usingSystem.Collections.Generic;/// <summary>///to assemble a computer as an example///The composition of each computer is consistent, but using the same build process can create different representations (that can be assembled into dissimilar computers, the configuration is not the same)///This scenario of assembling a computer can be used to design a builder model/// </summary>namespacebuilderpattern{/// <summary> ///Customer Class/// </summary> classCustomer {Static voidMain (string[] args) { //customers find computer City boss said to buy a computer, here to install two computers//Create a leader and a constructor varDirector =NewDirector (); Builder B1=NewConcreteBuilder1 (); Builder B2=NewConcreteBuilder2 (); //The boss asked the staff to assemble the first computer.Director. Construct (B1); //Assembled , assembled and assembled.Computer Computer1 =B1. Getcomputer (); Computer1. Show (); //The boss asked the staff to assemble the second computer.Director. Construct (B2); Computer Computer2=B2. Getcomputer (); Computer2. Show (); Console.read (); } } /// <summary> ///Xiao Wang and Xiao Li will volunteer to assemble, who do not want to rest, this must have a person to ask them to assemble to go to///This man is, of course, the boss, the leader in the builder's model .///command creation Process class/// </summary> Public classDirector {//assembling a computer Public voidConstruct (builder builder) {Builder. Buildpartcpu (); Builder. Buildpartmainboard (); } } /// <summary> ///Computer class/// </summary> Public classComputer {//Collection of computer components Private ReadOnlyilist<string> _parts =Newlist<string>(); //to add a single component to a collection of computer components Public voidADD (stringPart ) {_parts. ADD (part); } Public voidShow () {Console.WriteLine ("the computer begins to assemble ...."); foreach(stringPartinch_parts) {Console.WriteLine ("Components"+ part +"already installed."); } Console.WriteLine ("computer's assembled."); } } /// <summary> ///Abstract Builder, this scenario is "assembler", which can also be defined as an interface ./// </summary> Public Abstract classBuilder {//Install CPU Public Abstract voidbuildpartcpu (); //Installed motherboard Public Abstract voidBuildpartmainboard (); //Of course there are components such as hard drives, power supplies and so on, omitted here//get the assembled computer Public Abstractcomputer Getcomputer (); } /// <summary> ///Specific creator, specific to the specific creator, for example: Installed small King Ah/// </summary> Public classConcretebuilder1:builder {ReadOnlyComputer _computer =Newcomputer (); Public Override voidbuildpartcpu () {_computer. ADD ("CPU1"); } Public Override voidBuildpartmainboard () {_computer. ADD ("Main Board1"); } Public OverrideComputer Getcomputer () {return_computer; } } /// <summary> ///Specific creator, specific to the specific creator, for example: Installed Xiao Li Ah///it's another computer./// </summary> Public classConcretebuilder2:builder {ReadOnlyComputer _computer =Newcomputer (); Public Override voidbuildpartcpu () {_computer. ADD ("CPU2"); } Public Override voidBuildpartmainboard () {_computer. ADD ("Main Board2"); } Public OverrideComputer Getcomputer () {return_computer; } }}
The code above has a detailed comment code, here is not too much explanation, you can refer to the code and comments to compare with real life examples, showing the above code running results:
The computer starts to assemble ... Component CPU1 assembled components main BOARD1 has installed the computer to assemble the computer began to assemble ... Component CPU2 assembled components main BOARD2 The computer is ready to assemble.
Iv. implementation of the builder model in. NET
The previous design pattern is in the. NET class library, is there an implementation of the builder pattern in the. NET class library? The answer to the question, however, is yes, in the. NET class Library,System.Text.StringBuilder(exists in the mscorlib.dll assembly) is the implementation of a builder pattern. However, its realization belongs to the evolution of the builder model, when the builder mode has no command role and abstract builder role, theStringBuilder class is the role of the concrete builder, also plays the role of the conductor and the abstract builder, the implementation of the construction pattern is as follows:
usingSystem;usingSystem.Collections.Generic;/// <summary>///Evolution of builders ' patterns///the role of the conductor and the abstract builder were omitted///at this time the concrete builder role played the role of the conductor and the builder of two/// </summary> Public classbuilder{//code for the specific builder role Private ReadOnlyProduct _product =NewProduct (); Public voidBuildparta () {_product. ADD ("Parta"); } Public voidBUILDPARTB () {_product. ADD ("PartB"); } PublicProduct getproduct () {return_product; } //code for the conductor role Public voidConstruct () {Buildparta (); BUILDPARTB (); }}/// <summary>///Product Category/// </summary> Public classproduct{//Product Components Collection Private ReadOnlyilist<string> _parts =Newlist<string>(); //Add a single component to the product components collection Public voidADD (stringPart ) {_parts. ADD (part); } Public voidShow () {Console.WriteLine ("the product begins to assemble ...."); foreach(stringPartinch_parts) {Console.WriteLine ("Components"+ part +"already installed."); } Console.WriteLine ("Product Assembly completed"); }}//at this point the client should also make corresponding adjustmentsclassclient{Private StaticBuilder _builder; Static voidMain (string[] args) {_builder=NewBuilder (); _builder. Construct (); Product Product=_builder. GetProduct (); Product. Show (); Console.read (); }}
V. Analysis of builders ' patterns
Key to the implementation of the construction model:
- In the Builder mode, the conductor deals directly with the client, and the conductor divides the client's request to create the product into a build request for each part, which is then delegated to the specific builder role, and the concrete builder's role is to complete the construction of the specific product, but it is not known to the customer.
- The builder pattern is primarily used to "step-through-build a complex object", where "step-by" is a fixed combination process, and the parts of the complex object are constantly changing (that is, the internal components of the computer are constantly changing, and the changes in this case vary, such as the size of the hard disk, the CPU is dual-core)
- The product does not require abstract classes, as the final product created by the build pattern may vary greatly, so it is unlikely that an abstract product class will be extracted.
- The abstract factory model described in the previous article addresses the need for a "series of products", while the builder model solves the needs of the "product segment".
- Since the Builder hides the assembly process for a specific product, it is necessary to change the internal representation of a product by implementing a specific builder, which will be able to respond well to changes in the requirements of the constituent components of the product.
Vi. Summary
Here, the builder pattern is finished, the builder pattern, which separates the construction of a complex object from its representation, so that the same build process can create different representations. The essence of the builder pattern is to make the assembly process (encapsulated by the conductor class for decoupling purposes) and to create specific product decoupling so that we don't have to care about how each component is assembled.
C # design Pattern-builder mode