Application scenarios
To create different types of objects based on different parameters, it is common to define multiple constructors for calling in different scenarios. But there is a better constructor method that we can implement using the builder mode (only if there are multiple constructor parameters ).
Example (automobile class and its builder)
Public class car {private final int seet; private final string engine; private final int Dormer; private final int speed; private final int color; public static class builder {private int seet; private string engine; // optional parameters private int Dormer; private int speed; private int color; Public Builder (INT Seet, string engine) {This. seet = seet; this. engine = engine;} public builder Dormer (INT Val) {This. dormer = val; return this;} public builder speed (INT Val) {This. speed = val; return this;} public builder color (INT Val) {This. color = val; return this;} public car build () {return new car (this) ;}}; private car (Builder) {This. seet = builder. seet; this. engine = builder. engine; this. dormer = builder. dormer; this. speed = builder. speed; this. color = builder. color ;}}
Demonstration of Automobile Manufacturing Process(Different cars need different parts ):
Public class main {public static void main (string [] ARGs) {car car1 = new car. builder (4, "power "). dormer (1 ). speed (1, 1000 ). color (0, 255 ). build (); car car2 = new car. builder (2, "awesome "). speed (1, 2000 ). color (0, 122 ). build ();}}
Isn't it cool to build freely in combination?
Extension To achieve better scalability, the builder class can be independent and inherit from a builder interface. In addition, as shown in the preceding example, builder re-defines the attributes of the car class, which consumes a certain amount of performance. Therefore, when there are few optional parameters, this builder mode is not recommended.