C # examples of the builder mode of the design mode,
In a software system, you sometimes need to create a complex object, and the complex object is composed of the molecular objects of each part through certain steps.
For example, in a procurement system, if a buyer needs to purchase a batch of computers, the computer is a complex object in this actual requirement, it is made up of CPUs, mainboards, hard disks, video cards, chassis, etc. If the purchasers need to assemble a computer at this time, the purchasers will be exhausted, here we can use the builder mode to solve this problem. We can encapsulate the assembly process of various computer components into a builder object, the builder only needs to return the product objects that have been built by all the components on the client. However, this is also true in real life. If a company wants to purchase a batch of computers, it is impossible for purchasers to buy components and organize them by themselves, at this time, the buyer only needs to say what kind of computer he wants to purchase, just like the boss of the Computer City. The boss of the Computer City will naturally send the assembled computer to the company.
1. Builder Mode
Separates the construction of a complex object from its representation, so that different representations can be created during the same construction process.
The builder mode separates the Construction Code from the representation code, so that the client does not have to know the details of the product composition, thus reducing the coupling between the client and a specific product.
Ii. Builder pattern class diagram
Iii. Implementation of builder Mode
In this example, the boss of the Computer City directly contacts the customer (that is, the buyer). However, the computer assembly is conducted by the boss to instruct the installer to assemble all the parts of the computer, the person responsible for product creation (here the product refers to the computer) is the installer of the Computer City. After clarifying this logical process, let's take a look at how to use code to express this logical process in real life:
Using System; using System. Collections. Generic ;////// Take the computer assembly as an example. // The composition process of each computer is consistent, however, different representations can be created using the same build process (that is, they can be assembled into different computers with different configurations) /// the builder mode can be used to design the computer assembly scenario ///Namespace BuilderPattern {//////Customer class ///Class Customer {static void Main (string [] args) {// The Customer finds the Computer City owner and says he wants to buy a computer, install two computers // create the conductor and constructor var ctor = new director (); Builder b1 = new ConcreteBuilder1 (); Builder b2 = new ConcreteBuilder2 (); // The Boss Asks the employee to assemble the first computer ctor. construct (b1); // after assembly, the assembled Computer computer1 = b1.GetComputer (); computer1.Show (); // The Boss Asks the employee to assemble the second Computer director. construct (b2); Computer computer2 = b2.GetComputer (); computer2.Show (); Console. read ();}}////// Will Mr. Wang and Mr. Li be assembled voluntarily? Who doesn't want to rest, this requires someone to ask them to assemble before they can. // Of course, this person is the boss, that is, the conductor in the builder mode. // command creation process class ///Public class Director {// assemble the computer public void Construct (Builder builder) {builder. BuildPartCpu (); builder. BuildPartMainBoard ();}}////// Computer type ///Public class Computer {// Computer component set private readonly IList
_ Parts = new List
(); // Add a single component to the public void Add (string part) {_ parts. add (part);} public void Show () {Console. writeLine ("the computer starts assembling ....... "); foreach (string part in _ parts) {Console. writeLine ("component" + part + "installed");} Console. writeLine ("Computer assembled ");}}///
/// Abstract builder. In this scenario, it is the "assembler", which can also be defined as an interface ///Public abstract class Builder {// install CPU public abstract void BuildPartCpu (); // install the main board public abstract void BuildPartMainBoard (); // Of course, there are also components such as hard disk and power supply, skipped here // obtain the assembled Computer public abstract Computer GetComputer ();}///
/// Specific creator. A specific person is the specific creator, for example, Xiao Wang ///Public class ConcreteBuilder1: Builder {readonly Computer _ computer = new Computer (); public override void BuildPartCpu () {_ computer. add ("CPU1");} public override void BuildPartMainBoard () {_ computer. add ("Main board1");} public override Computer GetComputer () {return _ computer ;}}///
/// Specific creator. The specific person is the specific creator, for example, Xiao Li. // another computer is installed ///Public class ConcreteBuilder2: Builder {readonly Computer _ computer = new Computer (); public override void BuildPartCpu () {_ computer. add ("CPU2");} public override void BuildPartMainBoard () {_ computer. add ("Main board2");} public override Computer GetComputer () {return _ computer ;}}}
The code above contains detailed comments, which are not explained here. You can refer to the code and comments to compare them with real-life examples and demonstrate the running results of the code above:
Computer assembly ...... Component CPU1 has been installed with the Main board1 has been installed with a computer assembled with the computer started to assemble ...... Component CPU2 has been installed component Main board2 has been installed computer assembly
IV. Implementation of the builder mode in. NET
The previous design pattern is implemented in the. NET class library. Is there any builder pattern in the. NET class library? However, the answer to the question is yes. In the. NET class library, System. Text. StringBuilder (with mscorlib. dll concentration) is an implementation of the builder mode. However, its implementation belongs to the evolution of the builder mode. At this time, the builder mode does not have the conductor role or the abstract builder role. The StringBuilder class assumes the role of a specific builder, it also plays the role of the conductor and the abstract builder. The implementation of the construction mode is as follows:
Using System; using System. Collections. Generic ;////// The evolution of the builder mode /// the conductor role and the abstract builder role are omitted /// at this time, the specific builder role assumes two roles: the conductor and the builder ///Public class Builder {// code of the specific Builder role private readonly Product _ product = new Product (); public void BuildPartA () {_ product. add ("PartA");} public void BuildPartB () {_ product. add ("PartB");} public Product GetProduct () {return _ product;} // code of the conductor role public void Construct () {BuildPartA (); buildPartB ();}}////// Product class ///Public class Product {// Product component set private readonly IList
_ Parts = new List
(); // Add a single component to the public void Add (string part) {_ parts. add (part);} public void Show () {Console. writeLine ("the product is being assembled ....... "); foreach (string part in _ parts) {Console. writeLine ("component" + part + "installed");} Console. writeLine ("Product Assembly completed") ;}// at this time, the Client also needs to adjust the class Client {private static Builder _ builder; static void Main (string [] args) {_ builder = new Builder (); _ builder. construct (); Product product = _ builder. getProduct (); product. show (); Console. read ();}}
V. Analysis of builder Models
Key points of the construction mode:
In the builder mode, the conductor directly deals with the client. The conductor divides the client creation product request into the construction request for each part, and then delegates the request to the specific builder role, the role of a specific builder completes the construction of a specific product, but is not known to the customer.
The builder mode is mainly used to "build a complex object by step", where "Step by Step" is a fixed combination process, the various parts of complex objects change frequently (that is to say, the internal components of the Computer change frequently. Here, the changes refer to changes such as the size of the hard disk and the CPU change from single-core to dual-core ).
Abstract classes are not required for products. As the final products created in the build mode may differ greatly, it is unlikely to extract an abstract product class.
The abstract factory model introduced in the previous article solves the changes in the needs of "Series Products", while the builder model solves the changes in the "product part.
Because the builder hides the assembly process of a specific product, to change the internal representation of a product, you only need to implement a specific builder, in this way, we can better cope with changes in product components.
Vi. Summary
Here, the introduction of the Builder mode is over. The Builder mode (Builder Pattern) separates the construction of a complex object from its representation, the same build process can create different representations. The essence of the builder mode is to decouple the assembly process (encapsulated by the conductor class to achieve decoupling) from the creation of specific products, so that we do not have to worry about how each component is assembled.