Configure your complex objects more elegantly - the Builder pattern

Basic introduction to Builder mode

In our projects, we often encounter more complex objects, if we use the traditional set method to construct this object. Development and maintenance costs will skyrocket. The Builder pattern is a creational pattern that creates a complex object step by step. It allows users to have more precise control over the construction process of objects without knowing the internal construction details.

UML diagram of Builder pattern

write picture description here

Product —– Product class
Builder —– Builder abstract class, generally implemented by subclasses to implement the specific assembly process
ConcreteBuilder — Concrete Builder class
Director —– Unified assembly process

Definition of Builder Pattern

Separating the construction of a complex object from its representation allows the same construction process to create different representations.

Simple code implementation

package com.lpoint.builder;

//构建一个Product的抽象类
public abstract class Person {
    protected String name;
    protected String sex;
    protected int age;
    protected Person(){

    }
    public void setName(String name) {
        this.name = name;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public abstract void setSex();

    @Override
    public String toString() {
        return "[" + name + "]:Age is " + age + ",sex is " + sex + ";";
    }
}
package com.lpoint.builder;
//创建一个具体的Product类
public class Student extends Person{

    protected Student(){

    }

    @Override
    public void setSex() {
        sex = "F";
    }

}
package com.lpoint.builder;
//Builder的抽象类
public abstract class Builder {
    public abstract Builder builderName(String name);
    public abstract Builder builderSex();
    public abstract Builder builderAge(int age);
    //创建具体的对象
    public abstract Person create();
}
package com.lpoint.builder;
//具体的Builder类
public class StudentBuilder extends Builder{
    private Person p = new Student();
    @Override
    public StudentBuilder builderName(String name) {
        p.setName(name);
        return this;
    }

    @Override
    public StudentBuilder builderSex() {
        p.setSex();
        return this;
    }

    @Override
    public StudentBuilder builderAge(int age) {
        p.setAge(age);
        return this;
    }

    @Override
    public Person create() {
        return p;
    }

}
package com.lpoint.builder;

public class Test {
    public static void main(String[] args) {
        Builder builder = new StudentBuilder();
        Person s = builder.builderAge(15)
                .builderName("Lisa")
                .builderSex()
                .create();
        System.out.println(s.toString());
    }
}

Through the above simple codes, we first instantiate a Builder object on the client side, and then create a Person object through some methods of the builder. Note that we have removed the role of Director here. In fact, in actual development, we abandon the Director object and create objects by chaining calls to the Builder object. This way the substructure is obviously simpler and clearer, and the specific initialization process is also The builder object is encapsulated inside. The client only needs to call the builder method and create it at the end.

Application of Builder mode in Android

I believe that many students have seen the chain call to the Builder by the client at the end, and they must be able to find that there are many similar operations in Android, the most typical of which is the construction of the Dialog object. There will be similar operations in some third-party libraries, such as the famous Universal-Image-Loader. Interested students can study their source code to deepen their understanding of the Builder mode, which will not be repeated here.

summary

In actual project development, we often encounter such complex object construction, and many of them are not only complicated by themselves, but also when the use environment of the object is more complicated. In order to prevent the object from exposing too much structure to the outside world and increase the difficulty of development and code maintenance, this Builder pattern can be used to encapsulate the construction and configuration methods of complex objects, and only the Builder methods that can be called in a chain can be exposed to the outside world. Of course everything has pros and cons. Let's briefly look at the advantages and disadvantages of the Builder pattern.

advantage

1.良好的封装性,使用建造者模式可以使客户端不必知道产品内部组成的细节。
2.建造者独立,容易扩展。

shortcoming

会产生多余的Builder对象,消耗了更多的内存。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324773325&siteId=291194637