Contents of article series (continuously updated) :
Chapter 1: Overview, Coupling, UML, Seven Principles, Detailed Analysis and summary (Based on Java)
Chapter two: Several implementations of singleton pattern And its destruction by reflection
【 Design Pattern 】 Chapter 3: A Simple factory, factory method pattern, abstract factory pattern 】
The Builder model is not that difficult
Chapter 5: What is a Prototype Pattern? Shallow fetch shallow copy and deep copy
Article 6: Look at the adapter pattern
[Design Pattern] Chapter 7: Understand the bridge pattern with me
[Design mode] Chapter 8: Drinking soy milk is decorator mode?
[Design Pattern] Chapter 9: Combination pattern to solve the problem of hierarchical structure
[Design mode] Chapter 10: Appearance mode, the joy of driving a small broken car
[Design mode] Chapter 11: Let’s take a look at the yuan model
[Design Mode] Chapter 12: explanation of agent mode in the ticket purchase scene
A quote
Note: If you want to directly read the definition and other theoretical content, you can directly jump to the second point
In life there are many scenes and today we want to say “the builder pattern” is very match, for example a computer consists of CPU, memory, video card, memory, mouse, keyboard, monitor, etc. A combination of content, we want to be a computer, we won’t be possible to do these parts, are generally not by telling sales company, Then it sends the production technician to do the designated accessories for you.
Regardless of who buys, who does, and who manages, we can analyze that the “process” of building a computer is stable. That is to say, no matter what configuration of the computer, these accessories are necessary, but the specific details are different. For example, your configuration is better, his is worse
But, as a buyer, I don’t care. I just tell you that I want a medium sized computer, and you “build” it and give it to me, which is the generic way of saying “builder”
Let’s take a step-by-step look at this computer example:
The second is to understand the builder model step by step through examples
First of all, no matter how to build, how to buy, a Computer class is a must, we randomly pick three components to demonstrate, CPU, memory, display, complement its get set toString method
/** * product: computer */
public class Computer {
private String cpu; // CPU
private String graphicsCard; / / memory
private String displayScreen; / / display
public String getCpu(a) {
return cpu;
}
public void setCpu(String cpu) {
this.cpu = cpu;
}
public String getGraphicsCard(a) {
return graphicsCard;
}
public void setGraphicsCard(String graphicsCard) {
this.graphicsCard = graphicsCard;
}
public String getDisplayScreen(a) {
return displayScreen;
}
public void setDisplayScreen(String displayScreen) {
this.displayScreen = displayScreen;
}
@Override
public String toString(a) {
return "Computer{" +
"cpu='" + cpu + '\' ' +
", graphicsCard='" + graphicsCard + '\' ' +
", displayScreen='" + displayScreen + '\' ' +
'} '; }}Copy the code
(1) The simplest and most direct way (not good)
So this is basically a non-technical method, so just new + set, okay
public class Test {
public static void main(String[] args) {
Computer computer = new Computer();
computer.setCpu("Intel Core I5 processor");
computer.setGraphicsCard("4 gb of memory");
computer.setDisplayScreen("14-inch 1080p 60Hz display"); System.out.println(computer.toString()); }}Copy the code
Print the result:
Computer{CPU =’ Intel Core i5 processor ‘, graphicsCard=’4g’, displayScreen=’14 inch 1080p 60Hz monitor ‘}
(II) The customer directly contact the production technical personnel
This way, needless to say, is not appropriate, so the technician (builder) here he is! But different technical personnel will make accessories are not the same, for example, some will do 144Hz display, and some specialize in 60Hz display, high and low configuration, different models of points
To this end, we abstract an abstract class from ComputerBuilder
/** * Computer builder */
public abstract class ComputerBuilder {
abstract void buildCpu(a); / / build the CPU
abstract void buildGraphicsCard(a); // Build memory
abstract void buildDisplayScreen(a); // Build the display
abstract Computer getComputer(a); // Get this computer
}
Copy the code
Let’s write a builder implementation, such as a low-configuration computer implementation
/** * low configuration computer */
public class LowConfigurationComputerBuilder extends ComputerBuilder {
private Computer computer;
public LowConfigurationComputerBuilder(a){
computer = new Computer();
}
@Override
void buildCpu(a) {
computer.setCpu("Intel Core I5 processor");
System.out.println("BuildCpu: Intel Core I5 Processor");
}
@Override
void buildGraphicsCard(a) {
computer.setGraphicsCard("8 gb of memory");
System.out.println(BuildGraphicsCard: 8GB of memory);
}
@Override
void buildDisplayScreen(a) {
computer.setDisplayScreen("1080p 60Hz display");
System.out.println("BuildDisplayScreen: 1080p 60Hz display");
}
@Override
Computer getComputer(a) {
returncomputer; }}Copy the code
Test it out:
public class Test {
public static void main(String[] args) {
// Create low configuration computer builder
LowConfigurationComputerBuilder builder = new LowConfigurationComputerBuilder();
builder.buildCpu();
builder.buildGraphicsCard();
builder.buildDisplayScreen();
Computer computer = builder.getComputer();
System.out.println("Built computer:"+ computer ); }}Copy the code
Execution Result:
BuildCpu: Intel Core i5 processor buildGraphicsCard: 8GB of memory buildDisplayScreen: 1080p 60Hz display build computers: Computer{CPU =’ Intel Core i5 processor ‘, graphicsCard=’ 8GB memory ‘, displayScreen=’1080p 60Hz monitor ‘}
(iii) Customers contact the sales company
Although the above method is stronger than the first one, it is obviously not very reasonable for the customer to contact the production technical personnel. The normal way is to contact the sales company first and tell them what configuration of the computer I want. I don’t want to deal with the details
public class SalesCompany {
public Computer buildComputer(ComputerBuilder builder){
builder.buildCpu();
builder.buildGraphicsCard();
builder.buildDisplayScreen();
returnbuilder.getComputer(); }}Copy the code
The test code
public class Test {
public static void main(String[] args) {
// Create low configuration computer builder
LowConfigurationComputerBuilder builder = new LowConfigurationComputerBuilder();
// Create a computer sales center
SalesCompany salesCompany = new SalesCompany();
// Specify a specific computer builder to complete the computer product
Computer computer = salesCompany.buildComputer(builder);
System.out.println("Built computer:"+ computer ); }}Copy the code
Now the code has been more perfect, that is, we buyers by contacting the computer sales center, and then the sales center to call the user wants the configuration of the builder, we just created a “low configuration computer builder”, if we want to switch to a medium configuration computer, how to do?
Now all you need to do is add a moderately configured computer Builder and implement the Builder abstract class
/** * low configuration computer */
public class MiddleConfigurationComputerBuilder extends ComputerBuilder {
private Computer computer;
public MiddleConfigurationComputerBuilder(a){
computer = new Computer();
}
@Override
void buildCpu(a) {
computer.setCpu("Intel Core I7 processor");
System.out.println("BuildCpu: Intel Core I7 Processor");
}
@Override
void buildGraphicsCard(a) {
computer.setGraphicsCard("16 gb of memory");
System.out.println(BuildGraphicsCard: 16GB of memory);
}
@Override
void buildDisplayScreen(a) {
computer.setDisplayScreen("2K 144Hz display");
System.out.println("BuildDisplayScreen: 2K 60Hz Display");
}
@Override
Computer getComputer(a) {
returncomputer; }}Copy the code
Test the
public class Test {
public static void main(String[] args) {
MiddleConfigurationComputerBuilder builder = new MiddleConfigurationComputerBuilder();
// Create a computer sales center
SalesCompany salesCompany = new SalesCompany();
// Specify a specific computer builder to complete the computer product
Computer computer = salesCompany.buildComputer(builder);
System.out.println("Built computer:"+ computer ); }}Copy the code
The results
BuildCpu: Intel Core I7 Processor buildGraphicsCard: 16GB of memory buildDisplayScreen: 2K 60Hz display Build computers: Computer{CPU =’ Intel Core I7 processor ‘, graphicsCard=’ 16GB memory ‘, displayScreen=’2k 144Hz monitor ‘}
In fact, at this point, an example of the Builder pattern is written, so let’s combine concepts to understand the Builder pattern in depth
The builder model
(1) Concept
The Builder pattern: Separates the construction of a complex object from its representation so that the same construction process can create different representations
-
In other words, the production process or composition of the product is unchanged, but each part can be chosen by itself, that is, its internal representation can be changed, which is also said to change and unchanged separation
-
In this case, the user only needs to specify the type of build to get them, and the process and details need not be known
(2) Advantages and disadvantages
First of all, this pattern has good encapsulation, construction and presentation are separated, each builder is independent of each other, conducive to decoupling and expansion, in line with the “open and closed principle” at the same time, customers do not need to know product details
But it’s this constant part of the product creation process that limits its scope of use, and if something changes inside the product later, the builder has to do the same, which is costly to maintain, right
(3) Structure
Based on the above structure, let’s describe each of the four roles (except the Client caller).
- Product (Product role) : A complex object composed of multiple components, the computer in the above example
- Builder: An interface/abstract class that contains abstract methods for creating the child parts of a product, and typically a method for returning results, as in the ComputerBuilder class above
- ConcreteBuilder: Concrete implementation classes of Builders, such as the concrete low and medium PC builders described above
- Director: Calls the part construction and assembly methods in the Builder object to create a complex object
- The commander does not contain specific product information
- It isolates the production processes of customers and objects
(IV) Applicable scenarios
- The order will affect the results of the same method. For example, when building a house, the foundation should be laid before the reinforcement and cement are put on the ground
- The same object can be assembled with different parts or parts, with different results
- Product classes have complex internal structures, and these product objects have commonalities