[Java design pattern] Java design pattern (four) builder pattern (Builder Pattern)

Contents of this article

1. Introduction to builder mode

1.1 What is the builder pattern

1.2 Applicable scenarios

1.3 Main function

1.4 Problems solved

Second, the realization of the builder mode

2.1 Class diagram

2.2 Code implementation

2.3 Role analysis


1. Introduction to builder mode

1.1 What is the builder pattern

The creator mode is also called the builder mode, which separates the construction of a complex object from its representation, so that the same construction process can create different representations. The creator mode hides the process of creating complex objects. It abstracts the process of creating complex objects, and dynamically creates objects with composite properties through subclass inheritance or overloading.

1.2 Applicable scenarios

Isolate the creation and use of complex objects, the same method, different execution sequences, and different event results. Multiple components can be assembled into one object, but the resulting running results are different. The product category is very complicated or the product category is different because of the different calling sequence. When initializing an object with different effects, there are too many parameters, or many parameters have default values.

The Builder mode is not suitable for creating highly differentiated product categories. The internal changes of products are complicated, which will lead to the need to define a lot of specific builder categories to achieve changes, increase the number of categories in the project, increase the difficulty of understanding the system and the operating cost. The product objects that need to be generated are: Complex internal structure, these product objects have commonality;

1.3 Main function

Users can directly create complex objects without knowing the construction process and details of the object.

The user only needs to give the type and content of the specified complex object; the builder mode is responsible for creating complex objects in order (hiding the internal construction process and details)

1.4 Problems solved

Convenient for users to create complex objects (no need to know the implementation process) code reusability & encapsulation (encapsulate & reuse the object construction process and details)

Example: build a car & buy a car.

Factory (builder mode): responsible for manufacturing cars (assembly process> process and details in the factory)

Car buyers (users): You only need to say what you need> model (type and content of the object), and then you can directly buy it >> to use (you don't need to know how the car is assembled (wheels, doors,> Engine, steering wheel, etc.))

Second, the realization of the builder mode

The code implementation examples of all design patterns can be viewed on Code Cloud, and those who are interested can check it. Code Cloud address: https://gitee.com/no8g/java-design-patterns

2.1 Class diagram

 

The Director class is added. This class is encapsulated in layers. The methods in the class are described as follows:

A Mercedes-Benz vehicle model is the only model to start ( Start ), stop (stop) method, the other engine sound, speakers are not ;

The B- type Mercedes-Benz car first starts the engine ( engine boom ) , then starts (star), then stops (stop), without a horn;

For the C- type BMW, the horn first sounds ( alarm ), then ( start ) , and then stops (stop) , the engine does not roar;

D models of the BMW car on a start (Start) , then ran all the way black, perpetual motion machine, the method does not stop, no horns, no engine roar;

E models, F models ... and so on, there can be a lot of start (Start) , stop (STOP) , speaker (Alarm) , engine roar (engine boom)

These four methods can be freely combined in this class. How many? It seems to be permutation and combination. This won’t count. I didn’t learn mathematics well in high school.

2.2 Code implementation

package com.iot.practice.designpattern.builder.builderpattern;

/**
 * <p>Client 此类用于:</p>
 * <p>@author:hujm</p>
 * <p>@date:2021年02月07日 10:51</p>
 * <p>@remark:这里是牛叉公司的天下,他要啥我们给啥</p>
 */
public class Client {

    public static void main(String[] args) {

        BuilderDirector builderDirector = new BuilderDirector();

        for (int i = 0; i < 10; i++) {
            builderDirector.getBenzAModel().run();
        }

        for (int i = 0; i < 10; i++) {
            builderDirector.getBenzBModel().run();
        }

        for (int i = 0; i < 10; i++) {
            builderDirector.getBMWCModel().run();
        }

        for (int i = 0; i < 10; i++) {
            builderDirector.getBMWDModel().run();
        }
    }
}
package com.iot.practice.designpattern.builder.builderpattern;

import com.iot.practice.designpattern.builder.BMWModel;
import com.iot.practice.designpattern.builder.BenzModel;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>BuilderPatternClient 此类用于:</p>
 * <p>@author:hujm</p>
 * <p>@date:2021年02月07日 9:56</p>
 * <p>@remark:</p>
 */
public class BuilderPatternClient {

    public static void main(String[] args) {
        // 客户告诉牛叉公司,我要这样一个模型,然后牛叉公司就告诉我老大,说要这样一个模型,这样一个顺序,然后我就来制造
        List<String> sequenceList = new ArrayList<>();

        // 客户要求,run的时候时候先发动引擎
        sequenceList.add("engine boom");
        // 启动起来
        sequenceList.add("start");
        // 开了一段就停下来
        sequenceList.add("stop");

        // 要一个奔驰车:
        BenzBuilder benzBuilder = new BenzBuilder();
        // 把顺序给这个builder类,制造出这样一个车出来
        benzBuilder.setSequence(sequenceList);
        // 制造出一个奔驰车
        BenzModel benzModel = (BenzModel) benzBuilder.getCarModel();
        // 奔驰车跑一下看看
        benzModel.run();

        // 按照同样的顺序,我再要一个宝马
        BMWBuilder bmwBuilder = new BMWBuilder();
        bmwBuilder.setSequence(sequenceList);
        BMWModel bmwModel = (BMWModel) bmwBuilder.getCarModel();
        bmwModel.run();
    }
}
package com.iot.practice.designpattern.builder.builderpattern;

import com.iot.practice.designpattern.builder.CarModel;

import java.util.List;

/**
 * <p>CarBuilder 此类用于:</p>
 * <p>@author:hujm</p>
 * <p>@date:2021年02月07日 9:40</p>
 * <p>@remark:要什么顺序的车,你说,我给建造出来</p>
 */
public abstract class CarBuilder {

    /**
     * 建造一个模型,你要给我一个顺序要,就是组装顺序
     *
     * @param sequence 组装顺序
     */
    public abstract void setSequence(List<String> sequence);

    /**
     * 设置完毕顺序后,就可以直接拿到这个车辆模型
     *
     * @return 车辆模型
     */
    public abstract CarModel getCarModel();
}
package com.iot.practice.designpattern.builder.builderpattern;

import com.iot.practice.designpattern.builder.BMWModel;
import com.iot.practice.designpattern.builder.BenzModel;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>BuilderDirector 此类用于:</p>
 * <p>@author:hujm</p>
 * <p>@date:2021年02月07日 10:12</p>
 * <p>@remark:导演安排顺序,生产车辆模型</p>
 */
public class BuilderDirector {

    private List<String> sequenceList = new ArrayList<>();

    private BenzBuilder benzBuilder = new BenzBuilder();

    private BMWBuilder bmwBuilder = new BMWBuilder();

    /**
     * A类型的奔驰车模型,先start,然后stop,其他什么引擎了,喇叭一概没有
     *
     * @return A类型的奔驰车模型
     */
    public BenzModel getBenzAModel() {
        // 清理场景,这里是一些初级程序员不注意的地方
        this.sequenceList.clear();

        // 这只BenzAModel的执行顺序
        this.sequenceList.add("start");
        this.sequenceList.add("stop");

        this.benzBuilder.setSequence(sequenceList);
        return (BenzModel) this.benzBuilder.getCarModel();
    }

    /**
     * B型号的奔驰车模型,是先发动引擎,然后启动,然后停止,没有喇叭
     *
     * @return B型号的奔驰车模型
     */
    public BenzModel getBenzBModel() {
        // 清理场景,这里是一些初级程序员不注意的地方
        this.sequenceList.clear();

        // 这只BenzBModel的执行顺序
        this.sequenceList.add("engine boom");
        this.sequenceList.add("start");
        this.sequenceList.add("stop");

        this.benzBuilder.setSequence(sequenceList);
        return (BenzModel) this.benzBuilder.getCarModel();
    }

    /**
     * C型号的宝马车是先按下喇叭(炫耀嘛),然后启动,然后停止
     *
     * @return C型号的宝马车
     */
    public BMWModel getBMWCModel() {
        this.sequenceList.clear();

        this.sequenceList.add("alarm");
        this.sequenceList.add("start");
        this.sequenceList.add("stop");

        this.bmwBuilder.setSequence(sequenceList);
        return (BMWModel) this.bmwBuilder.getCarModel();
    }

    /**
     * D类型的宝马车只有一个功能,就是跑,启动起来就跑,永远不停止,牛叉
     *
     * @return D型号的宝马车
     */
    public BMWModel getBMWDModel() {
        this.sequenceList.clear();

        this.sequenceList.add("start");

        this.bmwBuilder.setSequence(sequenceList);
        return (BMWModel) this.bmwBuilder.getCarModel();
    }

    /**
     * 这里还可以有很多方法,你可以先停止,然后再启动,或者一直停着不动,静态的嘛
     * 导演类嘛,按照什么顺序是导演说了算
     */
}
package com.iot.practice.designpattern.builder.builderpattern;

import com.iot.practice.designpattern.builder.BMWModel;
import com.iot.practice.designpattern.builder.CarModel;

import java.util.List;

/**
 * <p>BMWBuilder 此类用于:</p>
 * <p>@author:hujm</p>
 * <p>@date:2021年02月07日 9:53</p>
 * <p>@remark:给定一个顺序,返回一个宝马车</p>
 */
public class BMWBuilder extends CarBuilder{

    private BMWModel bmwModel = new BMWModel();

    @Override
    public void setSequence(List<String> sequence) {
        this.bmwModel.setSequenceList(sequence);
    }

    @Override
    public CarModel getCarModel() {
        return this.bmwModel;
    }
}
package com.iot.practice.designpattern.builder.builderpattern;

import com.iot.practice.designpattern.builder.BenzModel;
import com.iot.practice.designpattern.builder.CarModel;

import java.util.List;

/**
 * <p>BenzBuilder 此类用于:</p>
 * <p>@author:hujm</p>
 * <p>@date:2021年02月07日 9:49</p>
 * <p>@remark:各种设施都给了,我们按照一定的顺序制造一个奔驰车</p>
 */
public class BenzBuilder extends CarBuilder{

    private BenzModel benzModel = new BenzModel();

    @Override
    public void setSequence(List<String> sequence) {
        this.benzModel.setSequenceList(sequence);
    }

    @Override
    public CarModel getCarModel() {
        return this.benzModel;
    }
}

2.3 Role analysis

The entire program has been written, and it is concise and clear. This is the builder mode. There are several roles in the middle that need to be explained:

Client is Niu Cha Company, which is other modules or pages in specific applications;

CarModel and the two implementation classes BenzModel and BMWModel are called Product Class. This product class implements the template method pattern, that is, there are template methods and basic methods. Refer to the template method pattern in the previous section;

CarBuilder and the two implementation classes BenzBuilder and BMWBuilder are called Builder Class. In the above example, my team and I are responsible for building Benz and BMW car models in the specified order;

The Director class is called the Director Class, which is responsible for arranging the order of the existing modules, and then telling the Builder to start building. In the above example, it is our boss. The Client finds the boss and says I want this, this, and that type of vehicle model. , And then the boss passed the order to me, and my team and I began to build desperately, and the construction of a project was completed.

This builder mode is very similar to the factory mode, but remember that you can use it with ease:

The main function of the builder mode is the arrangement of the calling sequence of the basic methods, that is, these basic methods have been implemented;

The factory method focuses on creation. I create an object for what object you want, and the order of assembly is not what he cares about.

 

 

end!

Guess you like

Origin blog.csdn.net/weixin_44299027/article/details/113726556