当前位置:网站首页>4. creator mode
4. creator mode
2022-06-12 10:13:00 【A man who is rubbed on the ground by math every day】
List of articles
4. Creator mode ( Frequency of use :**)
1. The definition of builder pattern
The builder pattern separates the components themselves from their assembly process , Focus on how to create a complex object with multiple components step by step , The user only needs to specify the type of the complex object to get the object , Without knowing the details of its internal structure .
- Builder pattern : Separate the construction of a complex object from its representation , So that the same build process can create different representations .
The definition of builder pattern
Separate the client from the creation process of complex objects containing multiple parts , The client does not need to know the internal components and assembly of complex objects , You just need to know the type of builder you need
Focus on how to create a complex object step by step , Different builders define different creation processes
2. The structure of the builder model

3. The builder pattern includes the following 4 A character :
Builder( Abstract builder )
ConcreteBuilder( Specific builder )
Product( product )
Director( commander ): Command which product to create
4. The realization of builder mode
Typical complex object class code :
public class Product { private String partA; // Define the components , Components can be of any type , Including value types and reference types private String partB; private String partC; //partA Of Getter Methods and Setter Method ellipsis //partB Of Getter Methods and Setter Method ellipsis //partC Of Getter Methods and Setter Method ellipsis }Typical Abstract builder class code :
public abstract class Builder { // Create a product object protected Product product=new Product(); public abstract void buildPartA(); public abstract void buildPartB(); public abstract void buildPartC(); // Return product object public Product getResult() { return product; } }Typical concrete builder class code :
public class ConcreteBuilder1 extends Builder{ public void buildPartA() { product.setPartA("A1"); } public void buildPartB() { product.setPartB("B1"); } public void buildPartC() { product.setPartC("C1"); } }Typical conductor class code :
public class Director { private Builder builder; public Director(Builder builder) { this.builder=builder; } public void setBuilder(Builder builder) { this.builder=builer; } // Product construction and assembly methods public Product construct() { builder.buildPartA(); builder.buildPartB(); builder.buildPartC(); return builder.getResult(); } }Customer class code snippet :
…… Builder builder = new ConcreteBuilder1(); // It can be realized through the configuration file Director director = new Director(builder); Product product = director.construct(); ……
5. Example
A game software company decided to develop a multiplayer online game based on role-playing , Players can play a specific role in the virtual world in the game , Characters according to different game plots and Statistics ( For example, power 、 magic 、 Skills, etc ) Have different abilities , Characters will also have more powerful abilities as they upgrade . As an important part of the game , Need to design game characters , And with the upgrade of the game, new characters will be added . Through analysis, we found that , The game character is a complex object , It contains gender 、 Face and other components , Different types of game characters , Its gender 、 Person's face 、 clothing 、 Hair style and other external characteristics are different , for example “ The angel ” With a beautiful face and long hair with a shawl , And wearing a white skirt ; and “ Devil ” Extremely ugly , Keep a bald head and wear a dazzling black dress . No matter what kind of game character , Its creation steps are similar , You need to create its components step by step , Then assemble the components into a complete game character . Now use the builder mode to realize the creation of game characters .

The sample code
(1) Actor: Game characters , Act as a complex product object
(2) ActorBuilder: Game character builder , Act as an abstract builder
(3) HeroBuilder: Hero character builder , Act as a concrete builder
(4) AngelBuilder: Angel character builder , Act as a concrete builder
(5) DevilBuilder: Demon character builder , Act as a concrete builder
(6) ActorController: Character controller , Act as a commander
(7) Client: Client test class
Results and Analysis
If you need to change the role builder , Just modify the configuration file
When a new role builder needs to be added , Just add the concrete character builder as a subclass of the abstract character builder , Then modify the configuration file , The original code does not need to be modified , Fully comply with the opening and closing principle
<?xml version="1.0"?>
<config>
<className>designpatterns.builder.AngelBuilder</className>
</config>
6. Omit Director
Omit Director class ( Combine complex products with the process of creating products ( Static methods ) Embedded in the abstract Creator ,)
- Abstract Creator
public abstract class ActorBuilder {
protected static Actor actor = new Actor();
public abstract void buildType();
public abstract void buildSex();
public abstract void buildFace();
public abstract void buildCostume();
public abstract void buildHairstyle();
public static Actor construct(ActorBuilder ab) {
ab.buildType();
ab.buildSex();
ab.buildFace();
ab.buildCostume();
ab.buildHairstyle();
return actor;
}
}
Embed the commander in the abstract factory
- Usage method
……
ActorBuilder ab;
ab = (ActorBuilder)XMLUtil.getBean();
Actor actor;
actor = ab.construct();
……
7. The introduction of hook method
Hook method (Hook Method): The return type is usually boolean type , The method name is generally isXXX()
public abstract class ActorBuilder {
protected Actor actor = new Actor();
public abstract void buildType();
public abstract void buildSex();
public abstract void buildFace();
public abstract void buildCostume();
public abstract void buildHairstyle();
// Hook method
public boolean isBareheaded() {
return false;
}
public Actor createActor() {
return actor;
}
}
public class DevilBuilder extends ActorBuilder {
public void buildType() {
actor.setType(" Devil ");
}
public void buildSex() {
actor.setSex(" demon ");
}
public void buildFace() {
actor.setFace(" Ugly ");
}
public void buildCostume() {
actor.setCostume(" Black ");
}
public void buildHairstyle() {
actor.setHairstyle(" Bareheaded ");
}
// Covering hook method
public boolean isBareheaded() {
return true;
}
}
public class ActorController {
public Actor construct(ActorBuilder ab) {
Actor actor;
ab.buildType();
ab.buildSex();
ab.buildFace();
ab.buildCostume();
// The hook method is used to control the construction of products
if(!ab.isBareheaded()) {
ab.buildHairstyle();
}
actor=ab.createActor();
return actor;
}
}
8. Advantages and disadvantages
- advantage
The client doesn't have to know the details of the product's internal composition , Decouple the product itself from the product creation process , It enables the same creation process to create different product objects
Every concrete builder is relatively independent , It has nothing to do with other specific builders , So it's easy to replace specific builders or add new ones , Easy to expand , Comply with opening and closing principle
You can control the product creation process more precisely
- shortcoming
The products created by the builder model generally have more in common , Its components are similar , If there is a big difference between products , Not suitable for builder mode , Therefore, its scope of use is limited
If the internal changes of the product are complex , You may need to define many concrete builder classes to implement this change , It makes the system very large , It increases the understanding difficulty and operation cost of the system
9. Applicable environment of mode
The product objects that need to be generated have complex internal structures , These product objects usually contain multiple member variables
The properties of the product objects that need to be generated depend on each other , You need to specify its build order
The creation of an object is independent of the class that created it . The commander class was introduced in the builder pattern , Encapsulates the creation process in the commander class , Not in the builder and customer classes
Isolate the creation and use of complex objects , And allow the same creation process to create different products
边栏推荐
- Li Yang, a scientific and technological innovator and CIO of the world's top 500 group: the success of digital transformation depends on people. Decision makers should always focus on "firewood"
- Halcon combined with C # to detect surface defects -- affine transformation (III)
- FPGA基于DE2-115平台的VGA显示
- [CEGUI] log system
- Clickhouse column basic data type description
- Reading notes of the fifth cultivation
- The white paper "protecting our digital heritage: DNA data storage" was released
- [untitled]
- Circuitbreaker fuse of resilience4j - Summary
- 一测两三年,记测试交流经验的一些感想
猜你喜欢
Detailed explanation and use of redis data types: key and string types

1268_FreeRTOS任务上下文切换的实现

Auto. JS learning note 4: after autojs is packaged, most Huawei and other big brand mobile phones cannot be installed? This problem can be solved by using the simulator to remotely sign and package in

C 语言仅凭自学能到什么高度?

Strange error -- frame detected by contour detection, expansion corrosion, and reversal of opening and closing operation effect

001: what is a data lake?

markdown_图片并排的方案

UE4_以现成资源探索创建背景场景的方法

HALCON联合C#检测表面缺陷——仿射变换(三)

1268_ Implementation of FreeRTOS task context switching
随机推荐
Explication du principe d'appariement le plus à gauche de MySQL
Implementation principle of redisson distributed lock
[Wayland] Wayland agreement description
原始套接字使用
[MySQL] index invalidation and index optimization
JVM (VI) Virtual machine bytecode execution engine (with stack execution process and bytecode instruction table)
[CEGUI] resource loading process
003:what does AWS think is a data lake?
Explanation of the principle of MySQL's leftmost matching principle
004:aws data Lake solution
SAP HANA 错误消息 SYS_XSA authentication failed SQLSTATE - 28000
总有一根阴线(上影线)会阻止多军前进的脚步,总有一个阳线(下影线)会阻挡空军肆虐的轰炸
2021-09-15
[SQLite3] memory debugging
一文读懂Dfinity生态中的首个NFT平台:IMPOSSIBLE THINGS
7-13 underground maze exploration (adjacency table)
Data processing and visualization of machine learning [iris data classification | feature attribute comparison]
Jetpack architecture component learning (3) -- activity results API usage
There is always a negative line (upper shadow line) that will stop the advance of many armies, and there is always a positive line (lower shadow line) that will stop the rampant bombing of the air for
哈希表的理论讲解