Detailed Explanation of the Builder Mode: Build a KFC Package with Any Match

1. Summary

The Builder Pattern is one of the five creational design patterns 它将一个复杂对象的构建与其表示分离,使得同样的构建过程可以创建不同的表示. How to understand this sentence: the construction process of an object is essentially the construction process of all the member attributes contained in the object. The process is very troublesome. If all the code is defined in this class, the code will appear bloated or even unclear. Therefore, we can separate the attribute construction process of the class independently and use a separate class to carry it. This class is 建造者类.

Builder mode generally includes the following roles:

  • Product role: A complex object to be created, generally containing multiple components, generally providing a static builder()method to generate a builder.
  • Builder class: It is used to construct complex objects, flexibly create various components of the object, and generally contains build()methods to return the final object. Abstraction layers can be refined.
  • Commander: a non-essential role, which calls the builder's method to control the construction of complex objects, mainly used to encapsulate the construction process and implement code reuse.

advantage

  • The construction details of complex objects are hidden from clients.
  • By decoupling the product itself and the product creation process, the product creation process can be controlled more finely, so that the same creation process can create different product objects.
  • By introducing a conductor, the reuse of the construction process can be realized.
  • Builder-independent and easy to extend while improving code readability and maintainability.

shortcoming

  • The builder pattern increases the number of classes, thus increasing the complexity of the system.
  • When the composition of the product changes, the builder class needs to be modified synchronously.

Applicable scene

  • The object that needs to be generated has a complex internal structure with many attributes.
  • There are certain dependencies or constraints among the internal attributes of the objects that need to be generated.
  • Need to separate objects and object creation process.

2. Realization case

Build a KFC Meal

Suppose we need to build a KFC set meal, which contains at least n burgers, n snacks, and n drinks. Then there are many ways to combine such a set meal, such as single set meal, double set meal, family bucket, any combination, etc. Next, we use the builder mode to create such a package.

UML class diagram
insert image description here

Code

Reference source class implementation

org.apache.flink.connector.kafka.source.KafkaSourceBuilder
org.apache.flink.connector.jdbc.JdbcExecutionOptions.Builder

product category

The product is a KFC set meal, including burgers, snacks, drinks, and the quantity is not limited.

public class Product {
    
    
    private List<String> burgers;//汉堡
    private List<String> snacks;//小食
    private List<String> drinks;//饮料

    public Product(List<String> burgers, List<String> snacks, List<String> drinks) {
    
    
        this.burgers = burgers;
        this.snacks = snacks;
        this.drinks = drinks;
    }
	
    //创建一个建造者类
    public static ProductBuilder builder(){
    
    
        return new ProductBuilder();
    }
	
    //展示套餐中的内容
    public void showProduct() {
    
    
        int i=burgers.size();
        int j=snacks.size();
        int k=drinks.size();
        String res="已经创建了一份套餐,该套餐包含:"+"\n"
                +i+"个汉堡,"+burgers.toString()+"\n"
                +j+"份小食,"+snacks.toString()+"\n"
                +k+"瓶饮料,"+drinks.toString();
        System.out.println(res);
    }
}

builder class

The builder mainly includes the method of adding ingredients to the set meal, such as adding a specific burger addBurger, a specific bottle of drink addDrink, etc. to the set meal, and finally provides a method to return the created set build()meal

public class ProductBuilder {
    
    
    private List<String> burgers;
    private List<String> snacks;
    private List<String> drinks;

    public ProductBuilder() {
    
    
        this.burgers = new ArrayList<>();
        this.snacks = new ArrayList<>();
        this.drinks = new ArrayList<>();
    }

    public ProductBuilder addBurger(String burger){
    
    
        burgers.add(burger);
        return this;
    }

    public ProductBuilder addSnack(String snack){
    
    
        snacks.add(snack);
        return this;
    }

    public ProductBuilder addDrink(String drink){
    
    
        drinks.add(drink);
        return this;
    }

    public Product build(){
    
    
        return new Product(burgers,snacks,drinks);
    }
}

test class

Create a mix-and-match combo.

public class Test {
    
    
    public static void main(String[] args) {
    
    
        Product product=Product.builder()
                .addBurger("奥尔良汉堡")
                .addBurger("巧克力汉堡")
                .addSnack("薯条")
                .addDrink("中杯可乐")
                .build();
        product.showProduct();
    }
}

image-20230508170808438

Commander (optional)

If you consider code reusability, you can also create a commander class for building single-person packages, double-person packages, etc.

public class Director {
    
    
    //创建单人套餐
    public static Product createSingleProducts(){
    
    
        return Product.builder()
                .addBurger("奥尔良汉堡")
                .addSnack("薯条")
                .addDrink("中杯可乐")
                .build();
    }
    //创建双人套餐
    public static Product createDoubleProducts(){
    
    
        return Product.builder()
                .addBurger("奥尔良汉堡").addBurger("巧克力汉堡")
                .addSnack("薯条").addSnack("蛋黄派")
                .addDrink("中杯可乐").addDrink("热牛奶")
                .build();
    }
}

Create custom packages directly with Commander

public class Test {
    
    
    public static void main(String[] args) {
    
    
        //创建双人套餐
        Product product=Director.createDoubleProducts();
        product.showProduct();
    }
}

3. Summary

This article introduces the Java builder pattern in detail, and lets you easily grasp the principle and implementation of the builder pattern by simulating the case of building a KFC package. The Java builder pattern uses multiple simple objects to build a complex object step by step, and can finely control the creation of each property of the object. This pattern builder is independent of the product object and dedicated to the creation of the product, which can significantly improve the readability and maintainability of the code.

In short, the builder mode is one of the necessary skills for Java programmers, and mastering it will provide you with more opportunities in the field of software development. I hope this article can be helpful to you. If you like this article, don't forget to like and follow!


insert image description here

Guess you like

Origin blog.csdn.net/qq_36756227/article/details/130573245