当前位置:网站首页>[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

边栏推荐
- leetcode 120. 三角形最小路径和
- Backtracking / activity scheduling maximum compatible activities
- In the "ten billion blue ocean" database, each player can find a boat | c-position face-to-face
- 2021 go developer survey
- Knowledge of affairs
- 河北 黄金寨景区新增“AED自动除颤器”保障游客生命安全!
- Learnopongl notes (IV) - Advanced OpenGL II
- NVIDIA R & D director: how does AI improve chip design?
- Cisco Rui submitted the registration of sci tech Innovation Board: proposed to raise 600million yuan, with annual revenue of 222million yuan
- Microservices - use of Nacos
猜你喜欢

Mysql(九)Your password has expired. To log in you must change it using a client that supports expired

简单的C语言版本通讯录

【创建型模式】建造者模式

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

06 _ 全局锁和表锁 :给表加个字段怎么有这么多阻碍?
[mysql_11] addition, deletion and modification of data processing

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

Understanding of oauth2

Art plus online school: Sketch common sitting posture test questions, these three angles must be mastered~

高数_第6章无穷级数__马克劳林级数
随机推荐
思科瑞递交科创板注册:拟募资6亿 年营收2.22亿
How to play seek tiger, which has attracted much attention in the market?
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
Social software soul withdraws its IPO application: Tencent is a major shareholder
Lippon instrument software intern interview
B站高管解读财报:疫情对公司长期发展无影响 视频化趋势不可阻挡
深度解读:分布式系统韧性架构压舱石OpenChaos
Hot seek tiger, a list of eco economic models
Did you break the rules?
What is excess product power? Find the secret key of the second generation cs75plus in the year of the tiger
Iclr2022| small sample fine tuning method of language model based on differentiable hints
硬核分析懒汉式单例
回溯法/活动安排 最大兼容活动
Qualcomm WLAN framework learning (29) -- 6GHz overview
Find combination number (function)
基于 GateWay 和 Nacos 实现微服务架构灰度发布方案
Microservices - use of Nacos
企业开发如何写出优雅的二级分类【美团小案例】
IDEA2021.1版本安装教程
05 _ 深入浅出索引(下)