当前位置:网站首页>[creation mode] builder mode
[creation mode] builder mode
2022-06-11 15:23:00 【Evader1997】
Look at a picture and relax

I found a moving picture from Du Niang , It is clear that this is an assembly line . The Yellow worker is responsible for putting the box into the bag , The blue worker is responsible for sealing the bag . Everyone in the assembly line should know , Everyone is responsible for one process , A complete product needs to go through all the assembly line workers . This real-world example can just help you understand the builder model .
Builder pattern
《 Big talk design patterns 》 Definition : Builder pattern , Will be a complex object of Build is separate from its presentation , So that the same build process can create different representations
This definition may not be well understood by those who are exploring design patterns , It can be simply understood as ,new Is to combine the construction and representation of objects ,= The one on the left can be understood as , and = Dexter new Xxx(a,b) It's the production process . So the builder pattern separates the presentation from the production process , There are two advantages to this :
- One is to ensure that when creating complex objects ** The production steps are specified ,** It ensures that the created objects conform to the rules ( The following case will explain )
- The decoupling of product construction process is realized ( Client failed new To create the object )
Car making and car making manual cases
This case reflects Create different kinds of cars And Different kinds of car manuals . Say important things three times , This case is the construction of two types of products , It can better reflect some characteristics of the builder mode , You may not be able to understand it , It is recommended to read the code , I'll knock on it myself first , Then learn from the following analysis !
Project structure chart :《 Deep into design patterns 》 Case study

Entity class and car type enumeration :Car( automobile ),Manual( Car manual ),CarType( Car type enumeration )
The builder pattern is the creation pattern , The end result is the creation of objects , automobile (Car) And the car Handbook (Manual) Is the object to be created by the builder pattern in the case . Car type (CarType) It's a car (Car) A property required for creation .
// The sports car , City cars ,SUV
public enum CarType {
CITY_CAR, SPORTS_CAR, SUV
}
public class Car {
// Car type
private final CarType carType;
// Seat size
private final int seats;
// The engine
private final Engine engine;
// transmission
private final Transmission transmission;
// Travel meter
private final TripComputer tripComputer;
// Navigator
private final GPSNavigator gpsNavigator;
// fuel
private double fuel = 0;
public Car(CarType carType, int seats, Engine engine, Transmission transmission, TripComputer tripComputer, GPSNavigator gpsNavigator) {
this.carType = carType;
this.seats = seats;
this.engine = engine;
this.transmission = transmission;
this.tripComputer = tripComputer;
if (this.tripComputer != null) {
this.tripComputer.setCar(this);
}
this.gpsNavigator = gpsNavigator;
}
public CarType getCarType() {
return carType;
}
public double getFuel() {
return fuel;
}
public void setFuel(double fuel) {
this.fuel = fuel;
}
public int getSeats() {
return seats;
}
public Engine getEngine() {
return engine;
}
public Transmission getTransmission() {
return transmission;
}
public TripComputer getTripComputer() {
return tripComputer;
}
public GPSNavigator getGpsNavigator() {
return gpsNavigator;
}
}
public class Manual {
private final CarType carType;
private final int seats;
private final Engine engine;
private final Transmission transmission;
private final TripComputer tripComputer;
private final GPSNavigator gpsNavigator;
public Manual(CarType carType, int seats, Engine engine, Transmission transmission, TripComputer tripComputer, GPSNavigator gpsNavigator) {
this.carType = carType;
this.seats = seats;
this.engine = engine;
this.transmission = transmission;
this.tripComputer = tripComputer;
this.gpsNavigator = gpsNavigator;
}
public String print() {
String info = "";
info += "Type of car: " + carType + "\n";
info += "Count of seats: " + seats + "\n";
info += "Engine: volume - " + engine.getVolume() + "; mileage - " + engine.getMileage() + "\n";
info += "Transmission: " + transmission + "\n";
if (this.tripComputer != null) {
info += "Trip Computer: Functional" + "\n";
} else {
info += "Trip Computer: N/A" + "\n";
}
if (this.gpsNavigator != null) {
info += "GPS Navigator: Functional" + "\n";
} else {
info += "GPS Navigator: N/A" + "\n";
}
return info;
}
}
Automotive components :Engine( The engine ),Transmission( transmission ),TripComputer ( Travel meter ),GPSNavigator( Navigator )
These classes / Enumeration corresponds to some components needed to build a car .
public class Engine {
// Volume
private final double volume;
// The mileage
private double mileage;
// start-up
private boolean started;
public Engine(double volume, double mileage) {
this.volume = volume;
this.mileage = mileage;
}
public void on() {
started = true;
}
public void off() {
started = false;
}
public boolean isStarted() {
return started;
}
public void go(double mileage) {
if (started) {
this.mileage += mileage;
} else {
System.out.println("Cannot go(), you must start engine first!");
}
}
public double getVolume() {
return volume;
}
public double getMileage() {
return mileage;
}
}
/** * transmission ( One speed , manual , automatic , semi-automatic ) */
public enum Transmission {
SINGLE_SPEED, MANUAL, AUTOMATIC, SEMI_AUTOMATIC
}
public class TripComputer {
private Car car;
public void setCar(Car car) {
this.car = car;
}
public void showFueLevel() {
System.out.println("Fuel level:" + car.getFuel());
}
}
public class GPSNavigator {
// Route
private String route;
public GPSNavigator() {
this.route = "221b, Baker Street, London to Scotland Yard, 8-10 Broadway, London";
}
public GPSNavigator(String manualRoute) {
this.route = manualRoute;
}
public String getRoute() {
return route;
}
}
Abstract builder and concrete builder :Builder( Abstract construction interface ),CarBuilder( Specific builder ),CarManualBuilder( Specific builder )
- Builder: Abstract construction interface , Defines how to build a car / All process methods of the manual
- CarBuilder: The specific builder of the car , Specific car builders , The interior provides a getResult() Method to get a Car object
- CarManualBuilder: The specific builder of the automobile manual , Specific manual builder , The interior provides a getResult() Method to get a Manual object
public interface Builder {
void setCarType(CarType type); // models
void setSeats(int seats); // seat
void setEngine(Engine engine); // The engine
void setTransmission(Transmission transmission); // transmission
void setTripComputer(TripComputer tripComputer); // hodometer
void setGPSNavigator(GPSNavigator gpsNavigator); // Navigator
}
public class CarBuilder implements Builder {
private CarType type;
private int seats;
private Engine engine;
private Transmission transmission;
private TripComputer tripComputer;
private GPSNavigator gpsNavigator;
@Override
public void setCarType(CarType type) {
this.type = type;
}
@Override
public void setSeats(int seats) {
this.seats = seats;
}
@Override
public void setEngine(Engine engine) {
this.engine = engine;
}
@Override
public void setTransmission(Transmission transmission) {
this.transmission = transmission;
}
@Override
public void setTripComputer(TripComputer tripComputer) {
this.tripComputer = tripComputer;
}
@Override
public void setGPSNavigator(GPSNavigator gpsNavigator) {
this.gpsNavigator = gpsNavigator;
}
public Car getResult() {
return new Car(type, seats, engine, transmission, tripComputer, gpsNavigator);
}
}
public class CarManualBuilder implements Builder {
private CarType type;
private int seats;
private Engine engine;
private Transmission transmission;
private TripComputer tripComputer;
private GPSNavigator gpsNavigator;
@Override
public void setCarType(CarType type) {
this.type = type;
}
@Override
public void setSeats(int seats) {
this.seats = seats;
}
@Override
public void setEngine(Engine engine) {
this.engine = engine;
}
@Override
public void setTransmission(Transmission transmission) {
this.transmission = transmission;
}
@Override
public void setTripComputer(TripComputer tripComputer) {
this.tripComputer = tripComputer;
}
@Override
public void setGPSNavigator(GPSNavigator gpsNavigator) {
this.gpsNavigator = gpsNavigator;
}
public Manual getResult(){
return new Manual(type, seats, engine, transmission, tripComputer, gpsNavigator);
}
}
Supervisor control generator :Director ( commander )
Three methods are defined in the commander , You can clearly see that the actual assignment is to the incoming builder , The three methods create different cars / manual , Is it a production vehicle or a production manual , The commander doesn't know , It depends on the specific builder . however No matter who the builder is , What the commander performs is an assembly line operation , As shown in the figure at the beginning , A brief analysis :
- constructSportsCar( Build sports cars ) Construction process :setCarType( Determine the vehicle type ) ------> setSeats( Build car seating capacity ) ------> setEngine( Build car engines ) ------> setTransmission( Build automobile gearboxes ) ------> setTripComputer( Build a car trip meter ) ------> setGPSNavigator( Build a navigator )
- constructCityCar( Building city cars ) Construction process :setCarType( Determine the vehicle type ) ------> setSeats( Build car seating capacity ) ------> setEngine( Build car engines ) ------> setTransmission( Build automobile gearboxes ) ------> setTripComputer( Build a car trip meter ) ------> setGPSNavigator( Build a navigator )
- constructCityCar( build SUV) Construction process :setCarType( Determine the vehicle type ) ------> setSeats( Build car seating capacity ) ------> setEngine( Build car engines ) ------> setTransmission( Build automobile gearboxes ) ------> setGPSNavigator( Build a navigator )
We found that building SUV There are only five steps , There is no such step as building a trip meter ( Actually a lot of SUV When leaving the factory, there is no travel meter , You need to add extra ). This example is just right here , That is to say, in the process of construction , Not all products need to complete the lottery builder (Builder) All the steps defined in , It can be realized on demand , It's very flexible .
Another advantage is The process of building objects is orderly , It is embodied in the following methods , We know that program execution is from top to bottom , This ensures that the objects created by the program are free of problems . Instead of using the builder pattern, we create a Car The flow of the object is :1, Take those components first new come out 2, Call again Car To create objects . So let's think about this , If the first 1 We have fewer objects in the three steps set A value , What happens ? So your component is incomplete , An incomplete component to build a car , Naturally, there is something wrong with this car . The builder pattern guarantees the integrity of the construction process by using the execution order of the code in a method .
public class Director {
public void constructSportsCar(Builder builder) {
builder.setCarType(CarType.SPORTS_CAR);
builder.setSeats(2);
builder.setEngine(new Engine(3.0, 0));
builder.setTransmission(Transmission.SEMI_AUTOMATIC);
builder.setTripComputer(new TripComputer());
builder.setGPSNavigator(new GPSNavigator());
}
public void constructCityCar(Builder builder) {
builder.setCarType(CarType.CITY_CAR);
builder.setSeats(2);
builder.setEngine(new Engine(1.2, 0));
builder.setTransmission(Transmission.AUTOMATIC);
builder.setTripComputer(new TripComputer());
builder.setGPSNavigator(new GPSNavigator());
}
public void constructSUV(Builder builder) {
builder.setCarType(CarType.SUV);
builder.setSeats(4);
builder.setEngine(new Engine(2.5, 0));
builder.setTransmission(Transmission.MANUAL);
builder.setGPSNavigator(new GPSNavigator());
}
}
summary
The actual development of the builder model is not common , But in JDK There is its shadow in , such as StringBuffer And StringBuilder Of append The method is to adopt the builder mode , The builder's model is inscrutable , In fact, we can realize the builder mode without a commander , This article does not expand . This pattern separates the object representation from the construction process , Realize decoupling , And ensure that complex objects ( The properties of an object are also objects ) Correctness of creation .
UML Class diagram

边栏推荐
- safePoint讲解及其安插思路分析
- 【SystemVerilog 之 验证】~ 测试平台、硬件设计描述、激励发生器、监测器、比较器
- [verification of SystemVerilog] ~ test platform, hardware design description, excitation generator, monitor and comparator
- 19. Insertion et suppression d'un arbre de recherche binaire
- Ali, tell me about the application scenarios of message oriented middleware?
- Mysql(九)Your password has expired. To log in you must change it using a client that supports expired
- Leetcode daily question - plus one
- [multi thread performance tuning] what operations cause context switching?
- 【创建型模式】原型模式
- Learn more about and use ThreadLocal
猜你喜欢

Qcustomplot 1.0.1 learning (3) - plotting quadratic functions

Did you break the rules?

【SystemVerilog 之 过程块和方法】~ 域、always过程块、initial过程块、函数 function、任务 task、生命周期

【SystemVerilog 之 验证】~ 测试平台、硬件设计描述、激励发生器、监测器、比较器

Qualcomm WLAN framework learning (29) -- 6GHz overview

LoveLive! Published an AI paper: generating models to write music scores automatically

企业开发如何写出优雅的二级分类【美团小案例】

07 _ Functions and disadvantages of row lock: how to reduce the impact of row lock on performance?

Station B executives interpret the financial report: the epidemic has no impact on the company's long-term development, and the video trend is irresistible
![[multi thread performance tuning] what operations cause context switching?](/img/a6/5d82c81dba546092447debebf7fc3e.jpg)
[multi thread performance tuning] what operations cause context switching?
随机推荐
02 Tekton Pipeline
Nexus configuration Yum repository for repository manager
uniapp开发微信小程序,从构建到上线
The reason why it is easy to let the single chip computer program fly
Talk about the principle of QR code scanning login
Exporting data using mysqldump
[SystemVerilog interface] ~ interface
Don't you understand the design and principle of thread pool? Break it up and crush it. I'll teach you how to design the thread pool
06 _ Global lock and table lock: Why are there so many obstacles to adding a field to a table?
How to batch insert 100000 pieces of data
19. 二叉搜索树的插入删除修剪
01discussion on Tekton
In the "ten billion blue ocean" database, each player can find a boat | c-position face-to-face
容易让单片机程序跑飞的原因
File is in use and cannot be renamed solution
简单的C语言版本通讯录
Implementation of gray-scale publishing scheme for microservice architecture based on gateway and Nacos
Lick the dog till the last one has nothing (linear DP)
uniapp開發微信小程序,從構建到上線
英伟达研发主管:AI 是如何改进芯片设计的?