当前位置:网站首页>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 .
边栏推荐
- Stackoverflow 年度报告 2022:开发者最喜爱的数据库是什么?
- The name of the button in the Siyuan notes toolbar has changed to undefined. Has anyone ever encountered it?
- Vxlan and MPLS: from data center to Metro Ethernet
- C語言實現掃雷(簡易版)
- 开放可编程基础设施(OPI)项目,重新定义DPU/IPU
- Apple, Microsoft and Google will no longer fight each other. They will work together to do a big thing this year
- 顺序表的基本操作
- Internet of things? Come and see Arduino on the cloud
- [suggested collection] time series prediction application and paper summary
- 科创人·味多美CIO胡博:数字化是不流血的革命,正确答案藏在业务的田间地头
猜你喜欢

图像PANR
![[video tutorial] functions that need to be turned off in win10 system. How to turn off the privacy option in win10 computer](/img/14/0313857adc178ecee4c866a05e54aa.jpg)
[video tutorial] functions that need to be turned off in win10 system. How to turn off the privacy option in win10 computer

Nodered has no return value after successfully inserting into the database (the request cannot be ended)

Mapstacks: data normalization and layered color layer loading

Difference between map and object

Image panr

微信小程序中使用vant组件

顺序表的基本操作

宅男救不了元宇宙

Set up your own website (14)
随机推荐
Map跟object 的区别
Set up your own website (14)
刚购买了一个MYSQL数据库,提示已有实例,控制台登录实例要提供数据库账号,我如何知道数据库账号。
RF_DC系统时钟设置GEN1/GEN2
Stop using system Currenttimemillis() takes too long to count. It's too low. Stopwatch is easy to use!
主数据建设的背景
[cann document express issue 04] unveiling the development of shengteng cann operator
年轻人捧红的做饭生意经:博主忙卖课带货,机构月入百万
lol手游之任务进度条精准计算
首个大众可用PyTorch版AlphaFold2复现,哥大开源OpenFold,star量破千
天天鉴宝暴雷背后:拖欠数千万、APP停摆,创始人预谋跑路?
顺序栈1.0版本
Accurate calculation of task progress bar of lol mobile game
Apple doesn't need money, but it has no confidence in its content
Behind Tiantian Jianbao storm: tens of millions in arrears, APP shutdown, and the founder's premeditated plan to run away?
宅男救不了元宇宙
Jd.com: how does redis implement inventory deduction? How to prevent oversold?
Fundamentals of performance testing -- definitions of common terms
消息称腾讯正式宣布成立“XR”部门,押注元宇宙;谷歌前 CEO:美国即将输掉芯片竞争,要让台积电、三星建更多工厂...
Dongyuhui is not enough to bring goods to "rescue" live broadcast