Design Mode learning 04-builder Mode

Source: Internet
Author: User
I. Motivation and definition
When creating an object, we know that we can use the factory method to create the object so that the caller can decouple the specific implementation. However, there is a situation where multiple objects to be created are highly repetitive, the factory model needs to be further evolved only when the creation steps, assembly sequence, or internal components are different. For example, there are many types of packages for KFC, for example, Package 1 (Fries + cola + hamburger), package 2 (chicken roll + fries + Cola), this package is the complex object we want to obtain, Then how do programs create such objects.
We can see that many of the Package content is the same. Can we consider how to extract a single food (such as chicken or cola, it is better to use a single category to coordinate the combination of these foods. The specific food creators are as follows:
// Food abstraction creator public abstract class foodbuilder {// package protected setmealproduct Sm = new setmealproduct (); // create a hamburger public abstract void buildhamburg (); // create fries public abstract void buildchips (); // create cola public abstract void buildcola (); // create chicken roll public abstract void buildchickenrolls (); Public setmealproduct getresult () {return SM ;}}
Specific food creators:
// Specific food Creator: KFC // in the future, McDonald's public class kfcfoodbuilder extends foodbuilder {@ override public void buildhamburg () {SM. getfoodlist (). add ("Hamburg") ;}@ override public void buildchips () {SM. getfoodlist (). add ("fries") ;}@ override public void buildcola () {SM. getfoodlist (). add ("Cola") ;}@ override public void buildchickenrolls () {SM. getfoodlist (). add ("chicken roll ");}}
Package products:
// Package public class setmealproduct {// package name private string name; // The food set Private list in the package <string> foodlist = new arraylist <string> (); public list <string> getfoodlist () {return foodlist;} public void setfoodlist (list <string> foodlist) {This. foodlist = foodlist;} Public String getname () {return name;} public void setname (string name) {This. name = Name ;}}
Classes responsible for generating packages and assembling the sequence:
// Package 1 (Fries + cola + Hamburg) Class firstdirector {private foodbuilder FB; Public firstdirector (foodbuilder FB) {This. fb = FB;} public setmealproduct construct () {FB. buildchips (); // fries FB. buildhamburg (); // Hamburg FB. buildcola (); // cola return FB. getresult () ;}// package 2 (chicken roll + fries + Cola) Class seconddirector {private foodbuilder FB; Public seconddirector (foodbuilder FB) {This. fb = FB;} public setmealproduct construct () {FB. buildchickenrolls (); // chicken roll FB. buildchips (); // fries FB. buildcola (); // cola return FB. getresult ();}}
Caller:
        FirstDirector fDirector = new FirstDirector( new KFCFoodBuilder());        SecondDirector sDirector = new SecondDirector( new KFCFoodBuilder());        fDirector.construct();        sDirector.construct();
In this way, the caller does not need to care about how to create the underlying layer, how to assemble it, and directly obtain it. In fact, this is the idea of the Creator mode.
Ii. Structure and class diagram
The builder mode is mainly used to create complex objects by step, separate these steps one by one, and use a conductor to control the order of these steps.

The builder mode has four roles: 1. Builder: Abstract builder, which defines the creation method of each part of the product, and how to build it by sub-class; 2. concretebuilder: Specific builder, creates each part and returns a created object. 3. ctor: the conductor, also called the Director, is responsible for assembling each part and executing the steps, and CALLS builder to create a specific product, it is the core of the builder model and has two responsibilities: one is to isolate the user and product generation process, the other is responsible for the product production process; 4. Product: specific product, A complex product composed of components.
3. Applicable scenarios and effects (advantages and disadvantages)
The builder mode is centered on the creator and the conductor. The Creator is responsible for the specific parts, parts or steps created, and the conductor is responsible for the steps, parts, assembly sequence, and quantity. Therefore, the builder mode can be considered in the following scenarios: 1. The product class is very complex. The components of the product class or the creation steps are relatively fixed, when you need to generate different product results based on different assembly methods or execution sequence, you can consider using the builder mode, such as the KFC example at the beginning, the parts (cola, chicken roll, etc.) are stable, the assembly method is unstable and does not generate a plan. Sometimes, you can consider using the template method in this case. The template method is simpler, but not as flexible as the builder; 2. The product category is very complex. The product component assembly method or creation steps are relatively fixed. When different components or steps are required to generate different products, that is to say, when we need to create different products using the same creation process, a common example is that in our daily life, we can assemble computers by ourselves. The computer assembly method is basically fixed, and the CPU, hard disk, memory, the video card is inserted into the motherboard, connected to the mouse and keyboard of the monitor, Boot, this step is what the conductor is doing, but the specific CPU is Intel or AMD, memory is not fixed, such as Kingston or Samsung. Providing CPU, memory, hard disk, and other components is what the Creator does. 3. The product category is very complex, The specific components and steps, assembly methods, and sequence change frequently. You can also use this mode. However, it is best to use it with other modes, such as using it with the template mode; 4. The attributes of the generated product objects are mutually dependent. You can consider the execution sequence when you need to specify them. Effects (advantages) after use: 1. encapsulation and decoupling, this is the basic role of the creation-type design pattern. It encapsulates the underlying layer. The caller does not need to know how to create a complex one, but needs to use it directly. 2. It is easy to expand and users can easily add specific builders. Users can use different builders to get different products. 3. The product assembly process, execution sequence, and specific parts and steps are separated, which is flexible and easy to expand new assembly methods and execution sequence. 4. The Builder mode can precisely control the creation process of complex products and better reflect the creation process of products than other creation modes. The specific steps of each Builder are independent, therefore, it can be further refined without affecting other modules. Disadvantage: if the internal changes of the product are complex, it may lead to the need to define many specific builders and commanders, resulting in a very large system. The builder mode generally creates products with many similarities, and the components are similar. If there is a large difference between products, the builder mode is not suitable.
V. Mode Scaling
1. Simplified mode. If the change lies in the conductor, assembly steps, and execution sequence, and there is only one builder, the abstract builder can be omitted. If the assembly method and steps are stable, you can omit the conductor and directly merge the steps into the builder. 2. You will find that the builder mode is very similar to the factory mode, but they are still different. The builder's main function is to assemble components and control the execution sequence of steps, that is, the component has been set. I will control the assembly method, and the focus of the factory model is to create and how to create specific components. It is not concerned about how to assemble them. You can refer to the example of computer assembly mentioned above. The Builder mode focuses on how to assemble, while the factory mode is on how to create CPU and memory. The factory model is more like an idea that delays uncertain and variable things to sub-classes for implementation (or for future implementation) to achieve some degree of decoupling. Abstract Factory is also an interface, but it is not because of uncertainty, but because of the product level. There are too many product families and it is encapsulated at a layer. The builder mode is not a construction mode. Some people say that renaming the "Director mode" reflects its nature better. Both are encapsulation. The builder is a procedural encapsulation and the factory is a structural encapsulation. 3. The Builder mode is often used in combination with other modes. For example, if it is used in combination with the template mode, a role in the builder mode is ignored and is a component, it is very suitable to use the template mode when creating parts. In addition, the creation of these components uses the factory mode and prototype mode, and sometimes controls the generation of class instances with a single instance. No matter what mode is used, no matter how combined, the ultimate goal must be to bring benefits to the system, rather than bloated structures and complex code. 4. Flexible Configuration Creation sequence. We can configure the conductor role in the builder mode to the configuration file, define unified standards, read the configuration file, and execute various methods of the Creator, in this way, it is very convenient to modify the execution sequence of the conductor. In fact, many modes can extract the steps to the configuration file. Although flexible, the code is complicated, and poor configuration file management is also a problem, which is also a trade-off. 5. Can only objects be created in builder mode? We have always said that the builder mode controls component assembly and the steps are executed in order to create objects. In fact, there is a deeper level. The execution sequence of the control steps is not only the creation of objects, but also the initialization of objects, even the execution steps of objects. For example, if we create a document object in the builder mode, we can obtain an opened document, an unopened document, or a document with some content initialized.
In summary, the builder mode breaks down the creation of complex objects into many small steps or widgets, and then uses the class of a conductor to control the execution of these steps or assembly of components, to achieve decoupling and scalability, callers only need to use command classes and build classes to encapsulate the creation of underlying objects. Because the builder is an abstract class rather than a specific implementation, subsequent extensions do not affect the existing code and comply with the open and closed principles.

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.