Java 23 design patterns of the Builder Builder pattern

Definition of:

Builder mode: Means to put aConstruction of complex objectsWith itssaidSeparate design patterns that allow the same build process to create different representations are called builder patterns.

It is the decomposition of a complex object into many simple objects, and then build step by step. It separates change from immutability, that is, the components of a product are constant, but each part can be flexibly selected

Second, the structure of Builder mode

1. Product role (Product) : It is a complex object containing multiple components, and each component is created by the concrete builder.

2. Abstract Builder: This is an interface that contains an abstract method to create the various child parts of the product, usually including a method getResult() that returns the product.

3. Concrete Builder: It realizes the Builder interface and completes the Concrete creation method of various parts of complex products

4. Director: It calls the component construction and assembly methods in the builder object to complete the creation of complex objects, and does not involve the information of specific products in the command

The aggregation relationship: Aggregation relation is a special correlation relation, which emphasizes the relation between the whole and parts, in which part can exist without the whole. For example, the relationship between a wild goose and a wild goose is an aggregation relationship. The wild goose can exist independently without the wild goose.

dependencies: Dependency relationship is a very weak relationship, usually refers to one class using another class, where students pick up money to the police uncle, students and police uncle is a kind of dependency relationship

Generalization relationshipGeneralization relation is also called inheritance relation in Java. In UML we represent it as a straight line with a hollow triangle. We add two classes, a ConcreteBuilder1 class and a ConcreteBuilder2 class, which inherit from the Builder class

Three: the implementation of Builder mode

1. We’re going to build a Product– assemble computers

2. Abstract Builder– install CPU, memory, hard disk and other abstract steps

ConcreteBuilder — the realization of the above abstract steps, such as install i5CPU, 8G memory, 1T hard disk

4. User Director — the person who installed the computer

(1) Product: computer

public class Computer { /*CPU*/ private String CPU; /* private String memory; Private String hardDisk; /* private String hardDisk; /* Keyboard */ private String Keyboard; /* Mouse */ private String Mouse; Public void setCPU(String CPU) {this.CPU = CPU; } public void setMemory(String memory) {this.memory = memory; } public void setThardDisk (String hardDisk) {this.hardDisk = hardDisk; } public void setKeyboard(String Keyboard) {this.Keyboard = Keyboard; } public void setMouse(String Mouse) {this.mouse = mouse; } @Override public String toString() { return "Computer{" + "CPU='" + CPU + '\'' + ", memory='" + memory + '\'' + ", hardDisk='" + hardDisk + '\'' + ", keyboard='" + keyboard + '\'' + ", mouse='" + mouse + '\'' + '}'; }}

(2) Abstract Builder class through the interface implementation, can also be through the abstract class

ComputerConfigBuilder {/* ComputerConfigBuilder {/* ComputerConfigBuilder {/* ComputerConfigBuilder {/* ComputerConfigBuilder {/* ComputerConfigBuilder {/* ComputerConfigBuilder {/* ComputerConfigBuilder {/* ComputerConfigBuilder {/* ComputerConfigBuilder {/* ComputerConfigBuilder; It also defines a method to get a Conputer for what the implementation class needs to do to install it. */ void setCPU(); void setMemery(); void setHardDisk(); void setKeyboard(); void setMouse(); // getComputer(); // getComputer(); }

Use abstract classes to do this

Public Abstract class ComputerConfigBuilder1 {public Abstract void setCPU(); public abstract void setMemery(); public abstract void setHardDisk(); public abstract void setKeyboard(); public abstract void setMouse(); Public abstract Computer getComputer(); public abstract Computer getComputer(); public abstract Computer getComputer(); }

(3) Create a low configuration version of the package LowConfigBuilder, let it implement ComputerConfigBuilder

Public class LowConfigBuilder implements ComputerConfigBuilder {// private Computer Computer; Public LowConfigBuilder() {this.Puter = new Computer(); } @Override public void setCPU() { computer.setCPU("i5"); } @Override public void setMemery() { computer.setMemory("8G"); } @Override public void setHardDisk() { computer.setHardDisk("500G"); } @override public void setKeyboard() {computer.setKeyboard(" keyboard "); } @Override public void setMouse() {Computer.setMouse (" Wire Mouse "); } /** @Override public Computer getComputer() {return Computer; }}

High matching assembly class

public class HighConfigBuider implements ComputerConfigBuilder{ private Computer mComputer; public HighConfigBuider(){ this.mComputer = new Computer(); } @Override public void setCPU() { mComputer.setCPU("i7"); } @Override public void setMemery() { mComputer.setMemory("16G"); } @Override public void setHardDisk() { mComputer.setHardDisk("1T"); } @override public void setKeyboard() {McOmputer.setKeyboard (" mechanical keyboard "); } @Override public void setMouse() {mComputer.setMouse(" wireless mouse "); } @Override public Computer getComputer() { return mComputer; }}

(4) An assembly Director is needed

public class Director { private ComputerConfigBuilder mBuilder; Public void setBuilder(ComputerConfigBuilder){this.mBuilder= Builder; this.mBuilder= Builder; } public void createComputer(){mBuilder.setCPU();} public void createComputer(); mBuilder.setMemery(); mBuilder.setHardDisk(); mBuilder.setKeyboard(); mBuilder.setMouse(); } public Computer getComputer(){return mBuilder.getComputer(); }}

(5) call

public class ThirdTeenActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_third_teen); Director director=new Director(); // Create Director. SetBuilder (new LowConfigBuilder()); // tell the installer the configuration of the computer, here is the low configuration director.createComputer(); Computer = director.getComputer(); Println (" Low PC configuration: "+computer.toString()); println(" System.out.println() "); Log.d("aa",computer.toString()); Director director1=new Director(); director1.setBuilder(new HighConfigBuider()); Director1.createComputer (); // Director1.createComputer (); Computer computer1=director1.getComputer(); Println (" Computer1.toString () + Computer1.toString ()); Log.d("aa",computer1.toString()); Computer{CPU='i5', memory='8G', hardDisk='500G', keyboard=' keyboard ', mouse=' wireline mouse '} aa: keyboard=' i5', keyboard=' wireline mouse ' Computer{CPU='i5', memory='8G', hardDisk='500G', keyboard=' keyboard ', mouse=' wire mouse '} System. OUT: Computer{CPU='i7', memory='16G', hardDisk='1T', keyboard=' mechanical keyboard ', mouse=' wirelessmouse '} Computer{CPU='i7', memory='16G', hardDisk='1T', keyboard=' mechanical ', mouse=' wirelessmouse '}

The Builder pattern needs to create an immutable Person object, which can have the following properties: name, sex, age, occupation, car, shoes, clothes, money, house. A name and gender are required.

Public class Person {/* Name (must) */ private final String name; /* gender (required) */ private final String gender; /* Age (not required) */ private final String age; Private final String shoes; /* private final String shoes; Private final String (); /* private final String (); /* private final String money; /* private final String money; Private final String house; /* private final String house; Private final String car; /* private final String car; /* Career (not required) */ private final String Career; private Person(Builder builder) { =; this.gender = builder.gender; this.age = builder.age; =; this.clothes = builder.clothes; =; =; =; =; } public static class Builder{private final String Name; private final String gender; private String age; private String shoes; private String clothes; private String money; private String house; private String car; private String career; public Builder(String name,String gender) { = name; this.gender = gender; } public Builder age(String age) { this.age = age; return this; } public Builder car(String car) { = car; return this; } public Builder shoes(String shoes) { = shoes; return this; } public Builder clothes(String clothes) { this.clothes = clothes; return this; } public Builder money(String money) { = money; return this; } public Builder house(String house) { = house; return this; } public Builder career(String career) { = career; return this; Public Person build(){return new Person(this); public Person build(){return new Person(this); }} public String toString() {return "Person{" + "name= "" + name +" \ "" + ", gender='" + gender + '\'' + ", age='" + age + '\'' + ", shoes='" + shoes + '\'' + ", clothes='" + clothes + '\'' + ", money='" + money + '\'' + ", house='" + house + '\'' + ", car='" + car + '\'' + ", career='" + career + '\'' + '}'; }} // Use Person Person =new Person.Builder("Rocky", "Male ").age("18").build(); System.out.println("person"+person); / / results System. Out: PersonPerson {name='Rocky', gender=' male ', age='18', shoes='null', clothes='null', money='null', house='null', car='null', career='null'}

Using Person here is like a product. The Builder inner class is equivalent to the Builder. Since the Person object is immutable, it’s no doubt that all of its properties will be final, but it can be left out without immutable requirements. Then define an inner class Builder in the Person class. The properties in the inner class Builder should be the same as those in the Person class, and the properties must be final in case these properties are not assigned. Other non-essential properties cannot be final, because if final is added, You have to initialize it so that the non-required properties become required again. The inner class then defines a constructor, passing in the required properties. The other non-required properties are set by methods, each of which returns the Builder object itself. Finally, we define a build method that passes the Builder object into Person’s private constructor and returns an object. Five: Android network Request OKHTTP3 to create Request information Request source code here using the variant of the Builder Builder model

Public Final Class Request {public Final Class Request {public Final Class Request {public Final Class Request {public Final Class Request {public Final Class Request {public Final Class Request} public Final Class Request {public Final Class Request} public Final Class Request {public Final Class Request} public Final Class Request {public Final Class Request} public Final Class Request {public Final Class Request} public Final Class Request {public Final Class Request} final String method; final Headers headers; final @Nullable RequestBody body; final Object tag; private volatile CacheControl cacheControl; // Lazily initialized. Request(Builder builder) { this.url = builder.url; this.method = builder.method; this.headers =; this.body = builder.body; this.tag = builder.tag ! = null ? builder.tag : this; } public HttpUrl () {return url;} public HttpUrl () {return url; } public String method() { return method; } public Headers headers() { return headers; } public String header(String name) { return headers.get(name); } public List<String> headers(String name) { return headers.values(name); } public @Nullable RequestBody body() { return body; } public Object tag() { return tag; } public Builder newBuilder() { return new Builder(this); } public String toString() {return "Request{method=" + method + ", URL =" + URL + ", Tag =" + (Tag! = this ? tag : null) + '}'; } public static class Builder { HttpUrl url; //url link String method; // Builder Headers (); Builder Headers (); // Request header requestBody body; // Request body Object tag; Public Builder() {this.method = "get "; public Builder() {this.method =" get "; this.headers = new Headers.Builder(); } Builder(Request request) { this.url = request.url; this.method = request.method; this.body = request.body; this.tag = request.tag; this.headers = request.headers.newBuilder(); } public Builder url(HttpUrl url) {if (url == null) throw new NullPointerException("url == null"); this.url = url; return this; }... Public Builder Header (String Name, String Value) {Headers. Set (Name, Value); return this; } //get request public Builder get() {return method(" get ", null); } // public Builder head() {return method(" head ", null); } // POST request public Builder POST (requestBody Body) {return method("POST", Body); } // where build creates the Request object, Public Request Build () {if (url == null) throw new IllegalStateException("url == null"); return new Request(this); }}} // Use Request MRequest =new Request.Builder().get().URL ("").build();

Advantages: I don’t need to know what your internals are, I can use Builder directly to build my own client; Code clear, easy to maintain, easy to expand; Separate construction and presentation to reduce coupling: Your code can also be unclear and difficult to maintain (say, your client implements many interfaces, and every time you change an interface, you have to change your client). Improper usage consumes memory

End: The only power to reach my goal is my perseverance.