Builder mode of Design Pattern
Use the factory mode to obtain simple objects.
It is better to use the builder mode when complex objects are obtained and some attributes of objects need to be configured in a complicated way.
Here we take building a car as an example. The components of the car can be freely matched.
package builder;public class Car {private String engine;private String tire;private String door;private String seat;public void setEngine(String engine) {this.engine = engine;}public void setTire(String tire) {this.tire = tire;}public void setDoor(String door) {this.door = door;}public void setSeat(String seat) {this.seat = seat;}@Overridepublic String toString() {return Car [engine= + engine + , tire= + tire + , door= + door + , seat= + seat + ];}public void show() {System.out.println(toString());}}
Package builder; public class CarBuilder {private Car car = new Car (); public CarBuilder addEngine (String engine) {car. setEngine (engine); return this;} public CarBuilder addTire (String tire) {car. setTire (tire); return this;} public CarBuilder addDoor (String door) {car. setDoor (door); return this;} public CarBuilder addSeat (String seat) {car. setSeat (seat); return this;}/*** first set the core component of the Car and then call this method */public car build () {return Car ;}}
Package builder; import org. junit. test; public class CarTest {@ Testpublic void test () {Car car = new CarBuilder ()//. addDoor (gorgeous door )//. addEngine (Gold engine )//. addSeat (comfortable seat )//. addTire (dazzling tires )//. build (); car. show ();}}
Similar builder uses a lot in android. In some framework configuration objects, you can also see the shadows of the builder mode.