Design pattern - Builder pattern usage example in Java

Scenes

builder mode

Assembly and creation of complex objects

No one buys only one tire or steering wheel when buying a car. What everyone buys is a complete car including multiple components such as tires, steering wheel and engine.

How to assemble these parts into a complete car and return it to the user is a problem that the builder mode needs to solve.

The builder pattern, also known as the generator pattern, is a relatively complex and relatively infrequently used creational pattern.

What the builder pattern returns to the client is not a simple product, but a complex product composed of multiple parts.

The builder pattern is a more complex creational pattern that separates the client from the creation of complex objects containing multiple components (or parts),

The client does not need to know the internal components and assembly methods of complex objects, but only needs to know the type of builder required.

It focuses on how to create a complex object step by step. Different specific builders define different creation processes.

And the specific builders are independent of each other, it is very convenient to add new builders without modifying the existing code, and the system has good scalability.

builder pattern example

Taking role-playing games as an example, game characters need to be designed, and new characters will be continuously added as the game is upgraded.

Different types of game characters have different external characteristics such as gender, face shape, and clothing.

Develop a small tool to create game characters, which can create different types of characters and add new characters flexibly.

A game character is a complex object, which includes multiple components such as gender and face shape. Different game characters have different components.

No matter what kind of game character it is, its creation steps are similar, and its components need to be created step by step.

Then assemble each component into a complete game character. How to create a complex object with multiple components step by step,

The builder pattern was born to solve such problems.

Builder mode structure diagram and role

Builder mode includes the following roles

Builder (abstract builder):
It specifies an abstract interface for creating each part of a product Product object. In this interface, two types of methods are generally declared. One type of method
is buildPartX(), which is used to create each part of a complex object;
the other type of method is getResult(), which is used to return complex objects.
Builder can be either an abstract class or an interface.

ConcreteBuilder (concrete builder):
It implements the Builder interface, realizes the specific construction and assembly methods of each component, defines and clarifies the complex objects it creates, and
can also provide a method to return the created complex product objects.
The buildPartX() method is implemented in ConcreteBuilder, and the member properties of the product object can be set by calling the setPartX() method of Product.
Different specific builders will have differences when implementing the buildPartX() method. For example, the parameters of the setPartX() method may be different. In some
specific builder classes, some setPartX() methods do not need to be implemented (an empty implementation is provided).
And these do not need to care about the client, the client only needs to know the specific builder type.

Product (product role):
It is a complex object that is built, containing multiple components, and a specific builder creates an internal representation of the product and defines its assembly process.
Complex objects refer to those objects that contain multiple member properties, which are also called components or parts, such as automobiles including steering wheel, engine, tires, etc., emails including sender, recipient, subject, content, attachments,
etc.

Director: The
director is also called the director class. It is responsible for arranging the construction order of complex objects. There is a relationship between the director and the abstract builder. In
its construct() construction method, the component construction and assembly methods of the builder object can be called to complete the construction of complex objects.
Generally, the client only needs to interact with the commander, determine the type of the specific builder on the client side, and instantiate the specific builder object (also through the configuration file and reflection mechanism), and then pass the object into the commander class through the constructor or Setter method of the commander class
.
This class has two main functions:
on the one hand, it isolates the customer from the creation process;
on the other hand, it controls the product creation process, including whether a certain buildPartX() method is called and the order in which multiple buildPartX() methods are called.
The commander programs for the abstract builder. The client only needs to know the type of the specific builder, and can call the relevant methods of the builder through the commander class to return a complete product object.
In real life, there is also a role similar to that of a commander. For example, when a customer buys a computer, the computer salesperson is equivalent to the commander. As long as the customer determines the type of computer, the computer salesperson can notify the computer assembler to assemble a computer for the customer
.

What is the difference between builder pattern and factory pattern?

The builder pattern is somewhat similar to the abstract factory pattern, but the builder pattern returns a complete complex product, while the abstract factory pattern returns a series of related products; in the abstract factory pattern, the client generates the required object by selecting a specific factory, while in the builder pattern, the client focuses on constructing a complex object step by step by specifying the specific builder type and instructing the Director class on how to generate the object, and then returns the
result
.
If the abstract factory pattern is regarded as an auto parts production plant that generates different types of auto parts, then the builder pattern is a car assembly plant that returns a complete car by assembling the parts.

Design patterns - examples of simple factory patterns, factory patterns, and abstract factory patterns in Java:

Design Patterns - Examples of Simple Factory Patterns, Factory Patterns, and Abstract Factory Patterns in Java_Java Factory Pattern Application Scenarios Examples_Overbearing Rogue Temperament Blog-CSDN Blog

Note:

Blog:
Overbearing rogue temperament blog_CSDN Blog-C#, Architecture Road, Blogger in SpringBoot

accomplish

The following uses the builder mode to realize the above character design process

1. Create a new Actor to act as a complex product. Here, lombok is used to omit the get and set methods.

import lombok.Data;

/**
 * 充当复杂产品
 */
@Data
public class Actor {
    //角色类型
    private String type;
    //性别
    private String sex;
    //脸型
    private String face;
    //服装
    private String costume;
}

2. Create a new abstract constructor, ActorBuilder, and add a new method to return a complete game character object

/**
 * 抽象构造者
 */
public abstract class ActorBuilder {

    protected Actor actor = new Actor();

    public abstract void buildType();
    public abstract void buildSex();
    public abstract void buildFace();
    public abstract void buildContume();

    //工厂方法,返回一个完整的游戏角色对象
    public Actor createActor(){
        return actor;
    }
}

3. The specific builder has three roles: hero, angel, and demon

Hero role constructor implementation

/**
 * 英雄角色建造器:具体建造者
 */
public class HeroBuilder extends ActorBuilder {

    @Override
    public void buildType() {
        actor.setType("英雄");
    }

    @Override
    public void buildSex() {
        actor.setSex("男");
    }

    @Override
    public void buildFace() {
        actor.setFace("帅气");
    }

    @Override
    public void buildContume() {
        actor.setCostume("盔甲");
    }
}

Angel character constructor implementation

/**
 * 天使角色建造器:具体建造者
 */
public class AngelBuilder extends ActorBuilder{
    @Override
    public void buildType() {
        actor.setType("天使");
    }

    @Override
    public void buildSex() {
        actor.setSex("女");
    }

    @Override
    public void buildFace() {
        actor.setFace("漂亮");
    }

    @Override
    public void buildContume() {
        actor.setCostume("翅膀");
    }
}

Demon character constructor implementation

/**
 * 恶魔角色建造器:具体建造者
 */
public class DeviBuilder extends ActorBuilder
{
    @Override
    public void buildType() {
        actor.setType("恶魔");
    }

    @Override
    public void buildSex() {
        actor.setSex("男");
    }

    @Override
    public void buildFace() {
        actor.setFace("吓人");
    }

    @Override
    public void buildContume() {
        actor.setCostume("皮衣");
    }
}

4. Create a new commander-role creation controller

/**
 * 角色创建控制器:指挥者
 */
public class ActorController{

    //逐步构建复杂产品对象
    public Actor construct(ActorBuilder builder){
        Actor actor;
        builder.buildType();
        builder.buildSex();
        builder.buildFace();
        builder.buildContume();
        actor = builder.createActor();
        return actor;
    }
}

5. The client calling method is as follows

        //针对抽象构造者编程
        ActorBuilder actorBuilder;
        //通过配置文件或其他方式获取具体的建造者
        actorBuilder = new HeroBuilder();
        ActorController actorController = new ActorController();
        Actor actor;
        actor = actorController.construct(actorBuilder);
        System.out.println(actor);

6. Summary

In the builder mode, the client only needs to instantiate the commander class, which is programmed for the abstract builder, and the client passes in the specific builder type as needed, and the director will
guide the specific builder to build a complete product step by step (step by step calling the
buildX() method of the specific builder). The same construction process can create completely different products. In the game character example, if you need to change the character
, you only need to modify the configuration file and replace the specific character builder class; if you need to add a new character, you can add a new specific character builder class
as a subclass of the abstract character builder, and then modify the configuration file. The original code does not need to be modified, which fully complies with the "open and close
principle".

The main advantages of the builder mode are as follows:
(1) In the builder mode, the client does not need to know the details of the internal composition of the product, and the product itself is decoupled from the product creation process, so that the
same creation process can create different product objects.
(2) Each specific builder is relatively independent and has nothing to do with other specific builders. Therefore, it is easy to replace specific builders
or add new specific builders. Users can obtain different product objects by using different specific builders. Since the commander class is
programmed for the abstract builder, adding a new concrete builder does not need to modify the code of the original class library, the system is easy to expand, and complies with the "open-close principle"
(3) The creation process of the product can be controlled more finely. Decomposing the creation steps of complex products into different methods makes the creation process
clearer and easier to use programs to control the creation process

The main disadvantages of the builder mode are as follows:
(1) The products created by the builder mode generally have more in common, and their components are similar. If the differences between products are large, for example,
many components are different, it is not suitable to use the builder mode, so its scope of use is limited.
(2) If the internal changes of the product are complicated, it may lead to the need to define many specific builder classes to realize this change, resulting in a very large system
, increasing the difficulty of understanding the system and increasing the operating cost.

Applicable scenarios
The builder pattern can be considered in the following situations:
(1) The product objects that need to be generated have complex internal structures, and these product objects usually contain multiple member attributes.
(2) The attributes of the product objects that need to be generated depend on each other, and the order of their generation needs to be specified.
(3) The creation process of an object is independent of the class that created the object. In the builder mode, by introducing the conductor class, the creation process is encapsulated
in the conductor class, not in the builder class and the client class.
(4) Isolate the creation and use of complex objects, and enable the same creation process to create different products.

Guess you like

Origin blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/131708520