当前位置:网站首页>Builder mode -- Master asked me to refine pills
Builder mode -- Master asked me to refine pills
2022-06-24 20:34:00 【zhanyd】
List of articles
Introduction
It is said that Xiaoshuai has worked hard for many years in Xiancao pharmacy at the foot of Huashan Mountain , From a handyman to a factory manager , Responsible for producing the treasure of the drugstore ---- Super black jade intermittent cream .
Super black jade intermittent cream is a rare secret medicine , It has the power to rebuild , Amazing , Its price is comparable to that of gold , Recover life immediately after taking 2500 spot , And it has super efficacy , Can recover at the same time 1000 Point internal force .
This medicine is so magical , The refining process is extremely complicated , And the quality is difficult to control , Although the medicine refining master in the factory has rich experience , But there is always something missing , It leads to good and bad effects of the product , The customer has many complaints about this . The master ordered Xiao Shuai to transform the process within three months , Put an end to such problems .
Xiaoshuai was ordered in the face of danger , Start work immediately , All the processes of super black jade intermittent cream have been sorted out :
- Prepare various precious medicinal materials in proportion
- Soak in the spring at the foot of Huashan Mountain for seven days and seven nights
- After soaking, add the secret medicine and mix well
- Refine 77 in the eight trigrams furnace for 49 days
- Dry on the top of Huashan Mountain for ten days , Absorb the essence of the sun and moon
- Put it into a special wooden box and seal it
Because the process flow is very complicated , Xiaoshuai made a list of the production process , Everyone follows this list , Whether it's an experienced teacher , Or the new apprentice , Follow the steps on the list strictly , There will be no mistakes .
As for how this list should be used in production ? Xiaoshuai used to be a programmer , The whole process is written in code , A design pattern is also used here , Let's have a look .
Construction mode
Maker mode (Builder Pattern): Separate the construction of a complex object from its representation , So that the same build process can create different representations .
( picture source :https://design-patterns.readthedocs.io/zh_CN/latest/creational_patterns/builder.html)
The builder pattern usually has two application scenarios :
- The steps of object creation are complicated , Step 1 is required 、 Two 、 Three or more steps are needed to create a successful
- The object itself has many properties , There may be constraints between attributes
Let's start with the first case of creating complex objects .
Make black jade intermittent cream
The code for making black jade intermittent cream is as follows :
Drug class :
/** * Drug class */
public class Drug {
/** * The name of the drug */
private String name;
/** * Whether it has been mixed */
private boolean isMixed;
/** * Whether it has been soaked */
private boolean isSoakd;
/** * Whether the secret medicine has been added */
private boolean hasSecretMedicine;
/** * Whether it has been refined */
private boolean isRefine;
/** * Whether it has been dried */
private boolean isDry;
/** * Whether it is sealed */
private boolean isSeal;
public Drug(String name) {
this.name = name;
}
@Override
public String toString() {
StringBuffer display = new StringBuffer();
display.append("---- get " + name + " Production situation ----\n");
display.append(" Whether it has been mixed :" + isMixed+ "\n");
display.append(" Whether it has been soaked :" + isSoakd+ "\n");
display.append(" Whether the secret medicine has been added :" + hasSecretMedicine+ "\n");
display.append(" Whether it has been refined :" + isRefine+ "\n");
display.append(" Whether it has been dried :" + isDry+ "\n");
display.append(" Whether it is sealed :" + isSeal+ "\n");
return display.toString();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isMixed() {
return isMixed;
}
public void setMixed(boolean mixed) {
isMixed = mixed;
}
public boolean isSoakd() {
return isSoakd;
}
public void setSoakd(boolean soakd) {
isSoakd = soakd;
}
public boolean isHasSecretMedicine() {
return hasSecretMedicine;
}
public void setHasSecretMedicine(boolean hasSecretMedicine) {
this.hasSecretMedicine = hasSecretMedicine;
}
public boolean isRefine() {
return isRefine;
}
public void setRefine(boolean refine) {
isRefine = refine;
}
public boolean isDry() {
return isDry;
}
public void setDry(boolean dry) {
isDry = dry;
}
public boolean isSeal() {
return isSeal;
}
public void setSeal(boolean seal) {
isSeal = seal;
}
}
Drug construction interface :
/** * Drug construction interface */
public interface DrugBuilder {
/** * blend */
public void mix();
/** * soak */
public void soak();
/** * Add the secret medicine */
public void addSecretMedicine();
/** * Refine */
public void refine();
/** * Airing */
public void dry();
/** * seal up */
public void seal();
}
Black jade intermittent cream builder class :
/** * Black jade intermittent cream builder class */
public class HeiYuDuanXuGaoBulider implements DrugBuilder{
private Drug drug;
public HeiYuDuanXuGaoBulider() {
this.drug = new Drug(" Black jade intermittent cream ");
}
/** * blend */
@Override
public void mix() {
this.drug.setMixed(true);
}
/** * soak */
@Override
public void soak() {
this.drug.setSoakd(true);
}
/** * Add the secret medicine */
@Override
public void addSecretMedicine() {
this.drug.setHasSecretMedicine(true);
}
/** * Refine */
@Override
public void refine() {
this.drug.setRefine(true);
}
/** * Airing */
@Override
public void dry() {
this.drug.setDry(true);
}
/** * seal up */
@Override
public void seal() {
this.drug.setSeal(true);
}
/** * Get medicines * @return */
public Drug getResult() {
return this.drug;
}
}
Deflector class :
/** * Deflector class */
public class Director {
/** * Build medicine * @param drugBuilder */
public void constructDrug(DrugBuilder drugBuilder) {
// blend
drugBuilder.mix();
// soak
drugBuilder.soak();
// Add the secret medicine
drugBuilder.addSecretMedicine();
// Refine
drugBuilder.refine();
// Airing
drugBuilder.dry();
// seal up
drugBuilder.seal();
}
}
Client class :
/** * Client class */
public class Demo {
public static void main(String[] args) {
// Create a deflector class
Director director = new Director();
// Create black jade intermittent paste builder class
HeiYuDuanXuGaoBulider heiYuDuanXuGaoBulider = new HeiYuDuanXuGaoBulider();
// Build medicine
director.constructDrug(heiYuDuanXuGaoBulider);
// Get medicines
Drug drug = heiYuDuanXuGaoBulider.getResult();
System.out.println(drug);
}
}
Running results :
---- get Black jade intermittent cream Production situation ----
Whether it has been mixed :true
Whether it has been soaked :true
Whether the secret medicine has been added :true
Whether it has been refined :true
Whether it has been dried :true
Whether it is sealed :true
DrugBuilder: Definition to create a Drug Object .
HeiYuDuanXuGaoBulider: Realization DrugBuilder The interface of , The interface method is implemented according to the characteristics of black jade intermittent paste .
Director: Guidance , Construction uses DrugBuilder Object of the interface , Follow the steps defined in the interface , Operate step by step , Produce drugs .
Drug: Represents the complex object to be constructed, i.e. black jade intermittent paste .
The client just calls Director Class constructDrug Method to create an object , The specific production steps and processes are determined by Director Class to control , It is transparent to the client , It greatly reduces the burden on the client .
Multiple parameters
lately , Some people in the Wulin say , They sometimes have medicine for internal injuries , But suffered trauma , Internal injury cannot be used for medicine , It will be wasted after the expiration date ;
If you have medicine for trauma , Sometimes I get internal injuries , It's also wasteful ;
If the medicine for internal injury and external injury is prepared at the same time , Will greatly increase the cost ( It's not easy to get involved in Jianghu now ), And generally, they will not suffer from internal injury and external injury ( That would be terrible ).
In order to improve the quality of service , To meet the personalized needs of customers , Xiaoshuai's master has recently developed a new product , The customer can deploy a portable alchemy stove for treating internal injury or trauma on site .
The principle is , Most of the ingredients of the medicine for internal injury and the medicine for external injury are the same , Only a small part is different , The medicine for internal injury is xianlingcao , The medicine for treating trauma is Dali pill .
So you just need to grind xianlingcao and Dali pill into powder , Pack in small bags , Bring it to the customer , Add xianlingcao or Dali pill as needed , Then use our special mixing pot to mix .
To meet individual needs , We also provide customers with sweet and salty flavors !
Said so much , Let's take a look at the code :
Drug class :
/** * Drug class */
public class Drug {
/** * The name of the drug */
private String name;
/** * Type of treatment (0: Treat internal injuries ;1: Treat trauma ) */
private int type;
/** * taste (1: sweet taste ;2: Salty ) */
private int taste;
/** * Drug particle size ( Company cm) */
private int size;
/** * Number */
private int num;
/** * Construction method , adopt Builder Class to construct objects * @param drugBuilder */
public Drug(DrugBuilder drugBuilder) {
this.name = drugBuilder.name;
this.type = drugBuilder.type;
this.taste = drugBuilder.taste;
this.size = drugBuilder.size;
this.num = drugBuilder.num;
}
@Override
public String toString() {
StringBuffer display = new StringBuffer();
display.append("---- You have obtained the medicine :" + name + " ----\n");
display.append(" Can treat :" + (type == 0 ? " Internal injury " : " Trauma ") + "\n");
display.append(" taste :" + (taste == 0 ? " sweet taste " : " Salty ") + "\n");
display.append(" Particle size :" + size + "cm\n");
display.append(" Number :" + num + " star \n");
return display.toString();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public int getTaste() {
return taste;
}
public void setTaste(int taste) {
this.taste = taste;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
Medicine construction :
public class DrugBuilder {
/** * The name of the drug */
public String name;
/** * Type of treatment (0: Treat internal injuries ;1: Treat trauma ) */
public int type;
/** * taste (1: sweet taste ;2: Salty ) */
public int taste;
/** * Drug particle size ( Company cm) */
public int size;
/** * Number */
public int num;
/** * Building drug objects * @return */
public Drug build() {
if(size < 1 || size > 5) {
throw new IllegalArgumentException(" The drug particle size must be within 1-5cm Between ");
}
if(num < 1 || size > 10) {
throw new IllegalArgumentException(" The quantity of drugs must be within 1-10 Between ");
}
return new Drug(this);
}
/** * Set the name * @param name * @return */
public DrugBuilder setName(String name) {
this.name = name;
return this;
}
/** * Set treatment type * @param type * @return */
public DrugBuilder setType(int type) {
this.type = type;
return this;
}
/** * Set taste * @param taste * @return */
public DrugBuilder setTaste(int taste) {
this.taste = taste;
return this;
}
/** * Set dimensions * @param size * @return */
public DrugBuilder setSize(int size) {
this.size = size;
return this;
}
/** * Set the number * @param num * @return */
public DrugBuilder setNum(int num) {
this.num = num;
return this;
}
}
Customer class :
public class Demo {
public static void main(String[] args) {
Drug drug = new DrugBuilder()
.setName(" Dali pill ")
.setType(1)
.setTaste(0)
.setSize(2)
.setNum(10)
.build();
System.out.println(drug);
}
}
Output :
---- You have obtained the medicine : Dali pill ----
Can treat : Trauma
taste : sweet taste
Particle size :2cm
Number :10 star
If the object to be created has many properties , And attributes have constraints , For example, the size must be in 1-5cm Between , Quantity must be within 1-10 Between , So it is more suitable to use the builder mode , Separate the properties and creation of objects .
This hides complex object building details for developers , Reduce the cost of learning , At the same time, it improves the reusability of the code .
The builder mode is JDK Application in source code
Let's take a look JDK Of StringBuilder class , You can tell from the name that it uses the creator mode , It provides append() Method , Open construction steps , Last call toString() Method to get a constructed complete string , The screenshot of the source code is as follows :
A use StringBuilder Example :
StringBuilder stringBuilder = new StringBuilder();
String str = stringBuilder
.append("a")
.append("b")
.append("c")
.toString();
summary
The builder mode is mainly applicable to the following application scenarios .
- Same method , Different order of execution , It produces different results .
- Multiple components or parts , Can be assembled into an object , But the results are different .
- The product category is very complex , Or different call orders in product classes have different effects .
- Initializing an object is particularly complex , There are many parameters , And many parameters have default values .
The difference between builder mode and factory mode
Both the builder pattern and the factory pattern are responsible for creating objects , So what's the difference between them ?
Factory pattern is used to create different but related types of objects ( Inherit a group of subclasses of the same parent class or interface ), The given parameters determine which type of object to create , Factory mode will immediately return the created object .
The builder pattern focuses on how to generate complex objects step by step , By setting different optional parameters ,“ Customized ” Create different objects , Allows you to perform some additional construction steps before getting the object .
You can see it , The purpose of the builder model is different from that of the factory model .
The advantages of builder mode
- Good encapsulation , Separation of construction and presentation .
- Comply with the single responsibility principle , You can separate complex construction code from the business logic of the product .
- Easy to control details , The builder can refine the creation process step by step , Without any impact on other modules .
Disadvantages of the builder model
- You need to add multiple classes , So the overall complexity of the code increases .
- If there is a change inside the product , Then the builder has to modify it simultaneously , Later maintenance costs are high .
Postscript
After Xiancao pharmacy launched a personalized pharmacy stove that can be carried around , He has won many praise in Wulin , We even developed Apple by ourselves , a mandarin orange , This pill tastes like peach , It set off an upsurge of making personalized pills , It also adds a lot of fun for Wulin people to wander the Jianghu .
边栏推荐
- 顺序栈1.0版本
- unity实战之lol技能释放范围
- unity之模糊背景(带你欣赏女人的朦胧美)
- Stop using system Currenttimemillis() takes too long to count. It's too low. Stopwatch is easy to use!
- 基于SSM的物料管理系统(源码+文档+数据库)
- "Ningwang" was sold and bought at the same time, and Hillhouse capital has cashed in billions by "selling high and absorbing low"
- Simulation lottery and probability statistics experiment of the top 16 Champions League
- lol手游之任务进度条精准计算
- 用自身细胞作为原料,首例3D打印耳朵移植成功!未来可打印更复杂器官
- 等保备案是等保测评吗?两者是什么关系?
猜你喜欢
16 excellent business process management tools
顺序栈遍历二叉树
主数据建设的背景
Q1: error in JMeter filename must not be null or empty
Bytebase joins Alibaba cloud polardb open source database community
实现基于Socket自定义的redis简单客户端
二叉树的基本性质与遍历
字节、腾讯也下场,这门「月赚3000万」的生意有多香?
Grating diffraction
网络安全审查办公室对知网启动网络安全审查,称其“掌握大量重要数据及敏感信息”
随机推荐
Compressed list of redis data structures
二叉树的基本性质与遍历
微信小程序自定义tabBar
C language to realize mine sweeping (simple version)
Openvino2022 dev tools installation and use
Apple, Microsoft and Google will no longer fight each other. They will work together to do a big thing this year
Basic properties and ergodicity of binary tree
VMware virtual machine setting static IP
Where is 5g really powerful? What is the difference with 4G?
You can capture fingerprints with a mobile camera?! Accuracy comparable to signature and monogram, expert: you are aggravating discrimination
gateway
maptalks:数据归一化处理与分层设色图层加载
Hosting service and SASE, enjoy the integration of network and security | phase I review
海泰前沿技术|隐私计算技术在医疗数据保护中的应用
Bytebase加入阿里云PolarDB开源数据库社区
网络安全审查办公室对知网启动网络安全审查,称其“掌握大量重要数据及敏感信息”
JMeter environment deployment
Batch capitalization of MySQL table names
宅男救不了元宇宙
How does the video platform import the old database into the new database?