Builder mode: in this mode, users do not need to know the details of internal construction, so they can better control the construction process. A complex object can have many parameters and components. The purpose of builder mode is to separate the process of creating this complex object from many parameters and components of the object, which has achieved the purpose of decoupling.
General process:
1. Privatize the construction method so that it can only be created by the build method of the internal class Builder
2. As a bridge, static internal class can set all parameters.
3. Create a Person instance by build ing.
4. Due to the bridge of Builder, different parameters can be set during the construction to decouple the construction and parameters.
5. After the instance is created, the parameters cannot be changed.
6. Hide the construction process. We can also add some processing during the construction process. These processing are all hidden. For example, in the following example, we can calculate whether the age is less than or equal to 18 years old.
As shown below: the Person class is constructed by passing in an instance of its internal class Build, and Build provides accessors for all its parameters, which users can freely combine according to their needs.
public class Person { private int ID; private int age; private String name; private int hight; private int weight; private Callback callback; interface Callback { void callback(); } private Person(Builder builder) { this.ID = builder.ID; this.age = builder.age; this.name = builder.name; this.hight = builder.hight; this.weight = builder.weight; this.callback = builder.callback; } public static class Builder { private int ID; private int age; private String name; private int hight; private int weight; private Callback callback; public Builder setID(int ID) { this.ID = ID; return this; } public Builder setAge(int age) { this.age = age; return this; } public Builder setName(String name) { this.name = name; return this; } public Builder setHight(int hight) { this.hight = hight; return this; } public Builder setWeight(int weight) { this.weight = weight; return this; } public Builder setCallback(Callback callback) { this.callback = callback; return this; } public Person build() { return new Person(this); } } }
Person.Builder buider = new Person.Builder(); buider.setAge(13); buider.setName("jack"); Person Tom = buider.build();