Design Mode (5) creator mode (Builder)

Source: Internet
Author: User

Design Mode (5) creator mode (Builder)
I. Schema Definition

Builder Pattern: 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 is used to create a complex object step by step. It allows users to build complex objects by specifying the types and content of complex objects. users do not need to know the specific internal building details. The builder mode belongs to the object creation mode. The builder mode can also be called the generator mode based on different Chinese translations.

Ii. Model motivation

Complex objects exist in both the real world and in software systems. They have multiple components, such as automobiles, including wheels, steering wheels, and senders. For most users, they do not need to know the Assembly details of these components or use a single component. Instead, they use a complete car, the builder mode can be used to design and describe components. The Builder mode can separate components from the assembly process and create a complex object step by step. You only need to specify the type of a complex object to obtain the object, without having to know the specific internal structure details.

In software development, there are also a large number of complex objects like cars. They have a series of member attributes, some of which are reference type member objects. In addition, some restrictions may exist in these complex objects. If some attributes are not assigned values, complex objects cannot be used as a complete product. Some attributes must be assigned values in a certain order, before an attribute is assigned a value, another attribute may not be assigned a value.

A complex object is equivalent to a car to be built, and the property of the object is equivalent to the parts of the car. The process of building a product is equivalent to the process of assembling parts. Because the process of assembling components is very complex, the combination process of these components is often "Externalized" into an object called builder, the builder returns a complete product object that has been built to the client, and the user does not need to care about the attributes contained in the object and how they are assembled. This is the model motivation of the builder mode.

Iii. pattern structure

It is quite common that there is only one product model structure below, which is also described in most books.

We can see that the Creator mode consists of four parts.

Abstract creator role: provides an abstract interface to regulate 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 creator role is used to directly create a product object. The specific creator must implement two methods for this interface: one is the construction method, the buildPart1 and buildPart2 methods in comparison, and the other is the result return method, that is, the getProduct method in the figure. In general, the number of parts contained in the product is consistent with the number of construction methods. In other words, how many parts are there is a corresponding construction method. Specific creator roles: they are responsible for creating product instances in the application. Tasks to be completed by this role include:
1. Implement the abstract method declared by the abstract creator, and provide step-by-step operations for product creation. 2. After creation, provide the product instance. Director role: This class calls a specific creator role to create a product object. However, 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 creator role. Product role: a product is a complex object during construction. Generally, a system has more than one product class, and these product classes do not necessarily have a common interface, but can be completely unrelated.

The process in the Creator mode is like this. When the client needs to create an object instance, it creates a director class and the creator of this object, and passes the Creator to the director class, the director class uses the Creator to create a specific product. However, the director class does not know how the product was created. The actual creation process of the product is determined by the specific factory. The specific factory is also divided into several steps during creation, the comparison shows two parts: part1 and part2, which correspond to the two parts of the product respectively. The specific factory is to create each part of the product through.

In actual applications, it is impossible to create a product only in the Creator mode. The following uses the two products as an example to discuss how to create multiple products in the Creator mode.

To create multiple products in the Creator mode, there is an implicit premise that these products share the same features, that is, they can be implemented through a common interface. For example, both Product1 and Product2 are inherited from AbstractProduct, and both products have part1 and part2. However, the implementation methods of part1 and part2 are different for each product, then you can use the Creator mode. In addition to this, it is also necessary to return the common parent class of the product in AbsractBuilder to ensure that the return of multiple products is normal.

Some people may wonder if a product consists of three parts and another product consists of two parts. Isn't it possible to use the Creator mode. No. You can also use the Creator mode to define three parts in the product class. Set this parameter to null if only two parts of the product do not belong to you.

Iv. instance analysis

We talked about the example of a local car manufacturer, but we haven't talked about how the local car was produced yet. We know that the production process of the car is very complicated, at the same time, cars are made up of many components. However, tuhao does not need to know how cars are made, how the parts are installed, and how to install them in any order. These tuhao do not need to know. So we should move this part of automobile production to a specific place.

Some may think that we can produce and assemble parts in the constructor of the Audi class, however, in this case, Benz and Bmw need to add the manufacturing parts and assembling functions to the constructor. First, it seems very troublesome, because each class adds a complicated piece of code. At the same time, we should realize that although the manufacturing details of Audi and Bnez are different, the general process is similar, everyone is made up of engines, tires, steering wheel, etc. Similar code is not elegant to repeat in different classes.

If the components of a product are the same, but the specific production details are different, the Creator mode is particularly suitable.

Package com. designpattern. builder;/*** abstract construction class, which provides the common interface for creating products, different products can have their own implementations * @ author **/public abstract class AbstractBuilder {/*** create engine */public abstract void buildEngine (); /*** create Vehicle Glass */public abstract void buildGlass ();/*** create a steering wheel */public abstract void buildSteeringWheel ();/*** return the created product, to be compatible with all products, the returned type is set to a common parent class * @ return */public abstract Car getCar ();}
Package com. designpattern. builder; /*** specific Audi creator * @ author xingjiarong **/public class AudiBuilder extends AbstractBuilder {/*** creates an object with all parts empty */Audi audi = new Audi (); /*** create each part */public void buildEngine () {audi. engine = AudiEngine;} public void buildGlass () {audi. glass = 3.5;} public void buildSteeringWheel () {audi. steeringWheel = AudiSteeringWheel;}/*** return the created object */public Car getCar () {return audi ;}}
Package com. designpattern. builder;/*** the Director class. Assemble the product * @ author xingjiarong **/public class Director {private AbstractBuilder build; public Director (AbstractBuilder build) according to the product construction and assembly sequence) {this. build = build;}/*** component method of the product. The process may be sequential * @ return */public Car construct () {build. buildSteeringWheel (); build. buildGlass (); build. buildEngine (); return build. getCar ();}}
Package com. designpattern. builder; public abstract class Car {/*** automobile engine, which should be an object in actual application. Here, a String is used to represent */public String engine;/*** Automobile Glass, different cars are of different sizes. You need to calculate */public double glass according to the car model;/* car steering wheel */public String steeringWheel; public abstract void drive ();}
Package com. designpattern. builder; public class Main {public static void main (String [] args) throws Exception {/*** create the director class and Audi builder */AudiBuilder build = new AudiBuilder (); director dire= new director (build);/*** use the Director class to get a Car instead of your own */car Car = director ctor. construct (); // drive the car. drive ();}}

Audi remains unchanged. The Benz car code is similar to that of the Audi car. instead of sticking to the specific code, the source code will be attached.

5. Advantages of the mode in the builder mode, the client does not have to know the details of the internal structure of the product, decoupling the product itself from the product creation process, so that different product objects can be created in the same creation process. Each specific builder is relatively independent of other specific builders, so it is easy to replace or add new specific builders, you can use different builders to obtain different product objects. You can more precisely control the product creation process. The creation steps of complex products are divided into different methods to make the creation process clearer and easier to use programs to control the creation process. New Concrete builders do not need to modify the code of the original class library. The conductor class is programmed for the abstract builder class, which facilitates system expansion and complies with the "open and closed principle ". 6. disadvantages of the model the builder model generally has many features in common and has similar components. If there are many differences between products, it is not suitable for the builder model, therefore, the scope of use is limited. If the internal changes of the product are complex, many specific builder classes need to be defined to implement such changes, resulting in a huge system. 7. Product objects to be generated in applicable scenarios have complex internal structures. These product objects usually contain multiple Member attributes. The property of the product object to be generated depends on each other, and the order of generation needs to be specified. The object creation process is independent of the class that creates the object. In the builder mode, the conductor class is introduced to encapsulate the creation process in the conductor class, rather than in the builder class. Isolate the creation and use of complex objects and allow different products to be created during the same creation process. VIII. Differences from abstract factory models

In the abstract factory model, each time a factory object is called, a complete product object is returned, and the client may decide to assemble these products into a larger and more complex product, or not. The building class is different. It builds a complex product at, and the product assembly process takes place within the Creator role. The builder's client obtains a complete final product.
In other words, the abstract factory model is at a more specific scale, while the builder model is at a more macro scale. A system can be composed of a construction mode and an abstract factory mode. by calling this creation role, the client indirectly calls the factory role of another abstract factory mode. Factory mode returns parts of different product families, while builder mode assembles them.

 

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.