当前位置:网站首页>Thoroughly understand the builder mode (builder)
Thoroughly understand the builder mode (builder)
2022-06-22 14:41:00 【happysnaker】
The article has been included in my warehouse :Java Share your study notes with free books
Design intent
To separate the construction of a complex object from its representation , So that objects can be created through different representations .
For example, a maze may have walls 、 Rooms and doors , And the quantity is not counted . The labyrinth may consist of only one wall , It may also consist of two walls , It may also be by 2 A room with a door … If the labyrinth is produced by heavy load , The amount of code is hard to count 、 Incomparably large .
Having a large number of components for an object ( A maze can have many walls or rooms or doors ), And the use of its components by constructing this object is uncertain ( Working with walls 、 room 、 The number of doors is uncertain ), Want fine-grained control over the build process , At this point, the builder mode can be used to solve the problem .
The intention of the builder pattern is to construct objects , So it belongs to the creation mode .
Applicable scenario
- During construction , The constructed objects have different representations .
- Some basic components don't change , And its combination often changes .
- The internal properties of the objects that need to be generated depend on each other .
Design
Assign a builder to the commander in chief , The commander in chief designs how to build , Actually built by the builder , Finally, the builder hands over the product to the commander in chief , The user completes the delivery from the commander in chief .
This process is very humanized , For example, our actual house decoration is the same , We asked some workers , Ask another worker leader to design and build ideas , Instruct these workers how to decorate , We only deal with the leaders of the workers next , The leader of the workers handed over the decorated house to us .

Code example
Consider the above maze problem :
// Define the maze class
class Maze {
public void setRoom(int x, int y, int roomId) {
System.out.println(" stay [" + x + "," + y + "] A building numbered " + roomId + " Room ");
// Keep relevant information
}
public void setDoor(int Id1, int Id2) {
System.out.println(" When the component number is " + Id1 + " And component number " + Id2 + " Build a door between ");
// Keep relevant information
}
public void setBarrier(int x, int y, int barrierId) {
System.out.println(" stay [" + x + "," + y + "] A building numbered " + barrierId + " The obstacles ");
// Keep relevant information
}
}
// Define the maze builder interface
interface MazeBuilder {
void buildRoom(int x, int y, int roomId);// Build a room
void buildDoor(int Id1, int Id2);// Building doors
void buildBarrier(int x, int y, int barrierId);// Build obstacles
Maze getMaze();// Get the end result
}
// Maze building team A, The way each construction team builds is different
class MazeBuilderA implements MazeBuilder {
// The construction team will gradually improve the maze , And deliver to customer
private Maze maze = new Maze();
@Override
public void buildRoom(int x, int y, int roomId) {
maze.setRoom(x, y, roomId);
}
@Override
public void buildDoor(int Id1, int Id2) {
maze.setDoor(Id1, Id2);
}
@Override
public void buildBarrier(int x, int y, int barrierId) {
maze.setBarrier(x, y, barrierId);
}
@Override
public Maze getMaze() {
return maze;
}
}
// Maze director class
class MazeDirecotr {
MazeBuilder mazeBuilder;
public MazeDirecotr(MazeBuilder mazeBuilder) {
this.mazeBuilder = mazeBuilder;
}
// Hand over the work to the commander , The user only needs to wait for the building to complete the removal of the instance
public Maze getMaze() {
// Specific design ideas are produced here
// Here we can construct a complex model step by step according to our ideas
// For example, here I want to build two rooms and a door in the middle
mazeBuilder.buildRoom(0, 0, 0);
mazeBuilder.buildRoom(0, 1, 1);
mazeBuilder.buildDoor(0, 1);
// The actual work is built by the workers
// The commander in chief obtains the final product from the workers , The chief commander shall complete the handover with the user
return mazeBuilder.getMaze();
}
}
// Test class
public class Test {
public static void main(String[] args) {
// Ask the workers to
MazeBuilder mazeBuilder = new MazeBuilderA();
// Please command , And hand over the workers to their command
MazeDirecotr mazeDirecotr = new MazeDirecotr(mazeBuilder);
// Finally, complete the product delivery with the commander in chief
Maze maze = mazeDirecotr.getMaze();
}
}
// Output
/* stay [0,0] A building numbered 0 Room stay [0,1] A building numbered 1 Room When the component number is 0 And component number 1 Build a door between */
Through the builder model , We no longer need to overload a large number of functions . By designing the director class, we can generate the desired objects step by step , The creation process can be more finely controlled . In development , The director class is defined by the user , An optimization technique is to use chained programming , We can define the builder interface as follows :
// Define the maze builder interface
interface MazeBuilder {
MazeBuilder buildRoom(int x, int y, int roomId);// Build a room
MazeBuilder buildDoor(int Id1, int Id2);// Building doors
MazeBuilder buildBarrier(int x, int y, int barrierId);// Build obstacles
Maze getMaze();// Get the end result
}
Then we can write code in the director class like this :
mazeBuilder.buildRoom(0, 0, 0).buildRoom(0,1,1).buildDoor(0, 1);
Summary of advantages and disadvantages
advantage :
1、 Independence of builders , Interface mode is adopted , Easy to expand .
2、 Easy to control detail risk .
3、 Decouple design from use , Easy to expand and maintain .
shortcoming :
1、 Products must have something in common , The scope is limited .
2、 If the internal changes are complicated , There will be a lot of construction classes .
** matters needing attention :** The difference from the factory model is : Builder mode pays more attention to the order of parts assembly .
边栏推荐
- Open source SPL redefines OLAP server
- 机器学习之支持向量机
- Messiari annual report-2021
- Network address translation nat
- 轻松上手Fluentd,结合 Rainbond 插件市场,日志收集更快捷
- transformers VIT图像模型向量获取
- Simple integration of client go gin IX create
- Maui uses Masa blazor component library
- Tianrun cloud is about to be listed: VC tycoon Tian Suning significantly reduces his holdings and is expected to cash out HK $260million
- If you want to know the stock account opening discount link, how do you know? Is it safe to open an account online?
猜你喜欢

天润云上市在即:VC大佬田溯宁大幅减持,预计将套现2.6亿港元

如何理解fold change?倍数分析?

【无标题】

Lisez ceci pour vous apprendre à jouer avec la cible de test de pénétration vulnhub - driftingblues - 5

Kukai TV ADB

Common real machine debugging plug-ins for unity commercial games

一文彻底弄懂工厂模式(Factory)

The diffusion model is crazy again! This time the occupied area is

Chip silicon and streaming technology

Biden signe deux nouvelles lois visant à renforcer la cybersécurité du Gouvernement
随机推荐
一文彻底弄懂建造者模式(Builder)
How many days are there between the two timestamps of PHP
C generic_ Generic class
D damage and safety
As a passer-by, some advice for programmers who are new to the workplace
C# Winform 相册功能,图片缩放,拖拽,预览图分页
Chengdu test equipment development_ Array introduction of C language for single chip microcomputer
Maui uses Masa blazor component library
Messari annual report-2022
How to implement interface exception scenario testing? Exploration of test methods and implementation of test tools
Offline physical stores combined with VR panorama make virtual shopping more realistic
MadCap Flare 2022,语言或格式的文档
如何理解fold change?倍数分析?
The diffusion model is crazy again! This time the occupied area is
一文彻底弄懂单例模式(Singleton)
【考研攻略】北京交通大学网络空间安全专业2018-2022年考研数据分析
C#泛型方法
[introduction to postgraduate entrance examination] analysis of postgraduate entrance examination data of Cyberspace Security Major of Beijing Jiaotong University from 2018 to 2022
[untitled]
3dMax建模笔记(一):介绍3dMax和创建第一个模型Hello world