current position:Home>Builder pattern of Java design pattern
Builder pattern of Java design pattern
2022-02-04 16:42:06 【Failed face】
Builder pattern : Use multiple simple objects to build a complex object step by step , It provides the best way to create objects .
The purpose of the builder mode : Separate the construction of a complex object from its representation , So that the same build process can create different representations .
advantage : Independence of builders , Easy to expand ; Easy to control detail risk .
Example scenario
In game development , hero Hero Represents a character , They work in different occupations Occupation In the form of , For example, you can change to a soldier or a shooter , Soldiers are equipped with long swords 、 Heavy armor , The archer is equipped with a bow 、 Leather .
Let's use the builder mode to create heroes of different classes , In this process, we should pay attention to the difference between the abstract factory pattern and the abstract factory pattern .
Create a hero and equipment interface class :
package com.cc.builder;
/**
* Hero interface class
* @author cc
* @date 21-12-19 11:48
*/
public interface Hero {
String name();
}
Copy code
package com.cc.builder;
/**
* Equipment interface class
* @author cc
* @date 21-12-19 0:24
*/
public interface Equip {
String name();
}
Copy code
Then there are the implementation classes of heroes and equipment :
package com.cc.builder;
/**
* Hero realization class : warrior
* @author cc
* @date 21-12-19 11:57
*/
public class Warrior implements Hero {
@Override
public String name() {
return "Warrior";
}
}
Copy code
package com.cc.builder;
/**
* Hero realization class : striker
* @author cc
* @date 21-12-19 11:58
*/
public class Shooter implements Hero {
@Override
public String name() {
return "Shooter";
}
}
Copy code
package com.cc.builder;
/**
* Equipment implementation class : Long sword
* @author cc
* @date 21-12-19 0:03
*/
public class Sword implements Equip {
@Override
public String name() {
return "Sword";
}
}
Copy code
package com.cc.builder;
/**
* Equipment implementation class : arch
* @author cc
* @date 21-12-19 0:04
*/
public class Bow implements Equip {
@Override
public String name() {
return "Bow";
}
}
Copy code
package com.cc.builder;
/**
* Equipment implementation class : Heavy armor
* @author cc
* @date 21-12-19 0:29
*/
public class HeavyArmor implements Equip {
@Override
public String name() {
return "Heavy Armor";
}
}
Copy code
package com.cc.builder;
/**
* Equipment implementation class : Leather
* @author cc
* @date 21-12-19 0:28
*/
public class LeatherArmor implements Equip {
@Override
public String name() {
return "Leather Armor";
}
}
Copy code
Then there is the professional entity class , This class contains information about heroes and equipment :
package com.cc.builder;
import java.util.ArrayList;
import java.util.List;
/**
* Professional entities
* @author cc
* @date 21-12-19 12:00
*/
public class Occupation {
private List<Equip> equips = new ArrayList<>();
private Hero hero;
public Occupation(Hero hero) {
this.hero = hero;
}
// Add equipment
public void addEquip(Equip equip) {
equips.add(equip);
}
// Display information
public void showInformation() {
System.out.println("Hero:" + hero.name());
for (Equip equip : equips) {
System.out.println(equip.name());
}
}
}
Copy code
Create a career builder class :
package com.cc.builder;
/**
* Professional builders
* @author cc
* @date 21-12-19 12:04
*/
public class OccupationBuilder {
// Build a warrior class
public Occupation prepareWarrior() {
Occupation occupation = new Occupation(new Warrior());
occupation.addEquip(new Sword());
occupation.addEquip(new HeavyArmor());
return occupation;
}
// Build a shooter class
public Occupation prepareShooter() {
Occupation occupation = new Occupation(new Shooter());
occupation.addEquip(new Bow());
occupation.addEquip(new LeatherArmor());
return occupation;
}
}
Copy code
Test it :
package com.cc.builder;
public class Main {
public static void main(String[] args) {
OccupationBuilder occupationBuilder = new OccupationBuilder();
{
Occupation occupation = occupationBuilder.prepareWarrior();
occupation.showInformation();
}
System.out.println("");
{
Occupation occupation = occupationBuilder.prepareShooter();
occupation.showInformation();
}
}
}
Copy code
result :
Hero:Warrior
Sword
Heavy Armor
Hero:Shooter
Bow
Leather Armor
Copy code
Builder pattern summary
Let's go back to our introduction to the builder model at the beginning of the above
The builder pattern uses multiple simple objects to build a complex object step by step , It provides the best way to create objects .
The purpose of the builder mode : Separate the construction of a complex object from its representation , So that the same build process can create different representations .
advantage : Independence of builders , Easy to expand ; Easy to control detail risk .
Copy code
- Our goal is to get a professional object , A single hero or equipment is only a part of this class , With the help of the builder model , We combine various simple objects into a complex object , The caller does not need to care about the specific creation process of the object , You only need to know one calling function 、 Object name or type
- In the test module, you can see , Same build process , You can create a specific representation of a warrior or shooter
- Independent and easy to expand , When we have new needs , Create a new builder class to , Basically no need to modify the original code . As in the example , We want to create a mage class , Can be in OccupationBuilder Add functions to the professional builder class , You can also create a new MasterOccupationBuilder.
The difference between builder pattern and abstract factory
In the previous article Java Factory mode of design mode in , We use all the soldiers in the game 、 An example of a shooter , In the process of learning the builder model , It's easy to confuse it with abstract factories , In fact, the difference between them is quite obvious , A closer look at the code of both shows that , In the abstract factory , Each factory function can create an object , They produce multiple products ; And the builder model , It is the sum of all creation functions that can implement an object , Corresponds to the... Described at the beginning : The builder pattern uses multiple simple objects to build a complex object step by step .
Builder pattern and usage scenario of abstract factory
Abstract factory : A series of related product objects can be combined to work , For example, a calculator that supports addition, subtraction, multiplication and division , Every function ( Add, subtract, multiply and divide ) Can be taken out separately , But in order to produce calculator products , Combine their product families by abstracting factories , We produce a calculator , You can have all the functions of addition, subtraction, multiplication and division .
builder : The car is a very complex object , It's through the wheel 、 body 、 Car door 、 Engine and other parts are assembled , A single component makes no sense , Assembling into an object is the goal .
Therefore, the builder mode is mainly used to create a scene of complex objects step by step , Focus on the details of the build process ; The abstract factory is used to create a series of products , Don't care about the build process , Only care about what factory it is produced by .
copyright notice
author[Failed face],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/02/202202041642033865.html
The sidebar is recommended
- What is the cost description of configuring data integration tasks between RDS and MySQL?
- What are the steps to configure the data integration task between RDS and MySQL?
- What are the data skew phenomena in MapReduce?
- What is the impact of stopping data integration tasks in DTS?
- What is the difference between quick Bi and power Bi in data source connection?
- What is the implementation principle of the four features of MySQL transactions?
- What is the impact of restoring data integration tasks in DTS?
- What are the fault tolerance methods in spark?
- What is the impact of deleting data integration tasks in DTS?
- What are the implementation ideas of transaction acid feature of MySQL?
guess what you like
-
What is the difference between quick Bi and power Bi in data processing and modeling?
-
What are the operational steps for managing data integration tasks in DTS?
-
What are the five advantages of spark?
-
What are the operation steps of modifying scheduling policy in DTS?
-
What are the similarities and differences between MapReduce and spark?
-
What are the differences between quick Bi and power Bi in visual presentation and report making?
-
How does MapReduce specify the number of CPUs at runtime?
-
How to write SQL to effectively use composite index?
-
What is the difference between quick Bi and power Bi on the mobile end?
-
How does MapReduce specify the size of runtime memory?
Random recommended
- What is the explanation of the scheduling policy in DTS?
- What are the instructions for modifying the scheduling effective date in DTS?
- What are the instructions for modifying the scheduling cycle in DTS?
- What are the streaming data writing functions in maxcompute?
- What will happen to the database self incrementing primary key?
- How does MapReduce tune the operating system?
- What are the performance advantages of streaming data writing in maxcompute?
- What is the description of modifying the task failure policy in DTS?
- How does MySQL master-slave replication work?
- What is the technical architecture of streaming data writing in maxcompute?
- What is the background information of monitoring alarm configured in DTS?
- What are the reasons for the delay of master-slave synchronization in MySQL?
- What are the operation steps for configuring monitoring alarms in DTS?
- Server in zookeeper A = B: C: D what do they mean?
- What is the query acceleration function in maxcompute?
- What is the solution to the master-slave synchronization delay of MySQL?
- What parameters are frequently adjusted when running MapReduce tasks?
- What is the technical architecture of query acceleration in maxcompute?
- What are the operation steps of viewing historical tasks in DTS?
- In 2020, Alibaba Android classic: after getting the offer, Alibaba fished up the resume again
- Summary of common knowledge points of Android interview in 2020, HashMap traversal
- 2020android will never die. As a programmer, what do you think is the biggest sorrow
- Linux system programming 43 file descriptor
- C + + date judgment blank filling is required to complete the blank filling
- About the parameter problem in Ajax, geigei help
- The number of daffodils in C language is wrong,
- UE4 carving terrain painting display problem
- Single chip C51 assembly language scatter program error
- Hello, let me ask Prometheus how to write port rules
- How can Linux ssh server solve the following problems
- (i++)+(--i)
- How about the Java debug mode? This is what I finally appeared.
- Linux operating system, online solution
- Calculate the value of the formula and display it on the screen
- What is the use of inter address access pointer access reference access
- There are two different pages in the front end. Add data on one page and refresh the data on the other page
- Find someone to teach me how to train somethingv2 on slowfast
- How can the statistics after pandas group by be output conditionally?
- Nlogit import data, whether in CSV or exclude format, not even the CSV format exported by Stata. Project import cannot import it
- Problems and solutions in the research and implementation of monitoring system testing in Universities Based on Servlet