The builder mode after the factory mode is also a common mode in java. It has a wide range of application scenarios and is easy to use.
If you want to know, let's have a look. 😁
I like the saying: "make a living within eight hours and survive outside eight hours."
Hello, if you like, please stick to it!!
I hope that when I meet you on the farewell day, you have achieved something.
Encourage each other
Look at the picture first to relieve your mood. 😁 I won't tell you that I am a little blogger who likes the blue sky, white clouds and sea 😀 )
1, Builder mode
1) Concept:
Builder pattern is a kind of design pattern, which separates the construction of a complex object from its representation, so that the same construction process can create different representations
Give a few examples in life:
There are many such examples in life. For example, different characters in the game have different gender, personality, ability, face shape, body shape, clothing, hairstyle and other characteristics; There are also a variety of steering wheel, engine, frame, tires and other components in cars; The sender, recipient, subject, content and attachment of each e-mail are also different.
For example, the computer is assembled by CPU, mainboard, memory, hard disk, graphics card, chassis, display, keyboard, mouse and other components. The purchaser cannot assemble the computer by himself, but tells the computer sales company the configuration requirements of the computer. The computer sales company arranges technicians to assemble the computer, and then gives it to the purchaser who wants to buy the computer.
In the process of software development, it is sometimes necessary to create a complex object, which is usually composed of multiple sub components according to certain steps.
2) Usage scenario:
- When the algorithm for creating a complex object should be independent of the components of the object and how they are assembled.
- When the construction process must allow different representations of the constructed object.
3) Role:
The Builder pattern contains the following roles:
- Abstract Builder class: this interface specifies the creation of those parts of complex objects, and does not involve the creation of specific component objects.
- Concrete Builder class: it implements the Builder interface and completes the specific creation method of various components of complex products. After the construction process is completed, an example of the product is provided.
- Product: complex object to create.
- Director: call the specific builder to create each part of the complex object. The director does not involve the information of the specific product, but is only responsible for ensuring that each part of the object is created completely or in a certain order.
4) Explanation:
- It separates the construction of components (in the charge of Builder) and assembly (in the charge of Director). Thus, complex objects can be constructed. Applicable to: the construction process of an object is complex.
- Because the decoupling of construction and assembly is realized, different builders and the same assembly can also make different objects; With the same builder, different assembly sequences can also make different objects. That is to realize the decoupling of construction algorithm and assembly algorithm, and realize better reuse.
- The builder pattern can separate the component from its assembly process and create a complex object step by step. Users only need to specify the type of complex object to get the object without knowing its internal specific construction details.
Illustration:
2, Code example
2.1 title
Create phone
The production of mobile phone is a complex process, which includes mobile phone chip, back shell, screen and other components. There are many kinds of mobile phone chips, such as Qualcomm and ios. There are also many kinds of glass and ceramics in the back shell, and the same is true for the screen.
Here, Phone is a product, including chip, back shell, screen and other components; Builder is an abstract builder, while IphoneBuilder and Huawei builder are concrete builders; Director is the commander.
2.2 class diagram
2.3 code
1. Phone (specific product category)
@Data public class Phone { /**Mobile phone chip*/ private String chip; /** Rear shell*/ private String backCover; /**screen*/ private String screen; }
2. Builder (Abstract builder class)
public abstract class Builder { protected Phone phone = new Phone(); public abstract void buildchip(); public abstract void buildbackCover(); public abstract void buildscreen(); public abstract Phone getPhone(); }
3. Huawei builder, IphoneBuilder (specific builder class)
public class HuaweiBuilder extends Builder{ @Override public void buildchip() { phone.setChip("Huawei says that the chip Kirin 9000"); } @Override public void buildbackCover() { phone.setBackCover("Glass rear shell"); } @Override public void buildscreen() { phone.setScreen("Domestic screen"); } @Override public Phone getPhone() { return phone; } }
public class IphoneBuilder extends Builder { @Override public void buildchip() { phone.setChip("Apple self research ios chip"); } @Override public void buildbackCover() { phone.setBackCover("Glass rear shell"); } @Override public void buildscreen() { phone.setScreen("iphone screen"); } @Override public Phone getPhone() { return phone; } }
4. Director (director class)
public class Director { private Builder builder; public Director(Builder builder) { this.builder = builder; } public Phone construct() { builder.buildchip(); builder.buildbackCover(); builder.buildscreen(); return builder.getPhone(); } }
The above example is the general usage of the Builder pattern. According to the system design, the design pattern will make some changes in some details. Of course, this is to make better use of the advantages of the design pattern. (it is inevitable to analyze and use specific problems) 😁
2.4 test
The code is the above, not much.
public class Client { public static void main(String[] args) { // Director director = new Director(new IphoneBuilder()); // If you want to change Huawei, you just need to change to Huawei builder without modifying other code Director director = new Director(new HuaweiBuilder()); Phone phone = director.construct(); System.out.println(phone); } }
3, Summary
advantage:
1) The builder model is well encapsulated. Using the builder mode can effectively encapsulate changes. In the scenario of using the builder mode, the general product class and builder class are relatively stable. Therefore, encapsulating the main business logic in the commander class can achieve better stability as a whole.
2) The client (user program) does not need to know the details of the internal composition of the product, decouples the product itself from the product creation process, so that the same creation process can create different product objects
3) You can more finely control the product creation process. The creation steps of complex products are decomposed into different methods, which makes the creation process clearer and easier to use programs to control the creation process
4) Adding a new specific builder does not need to modify the code of the original class library. The commander class is programmed for the abstract builder class, which is convenient for system expansion and conforms to the "opening and closing principle"
Disadvantages:
- The products created by Creator mode generally have more in common and their components are similar. If there are great differences between products, it is not suitable to use builder mode, so its scope of use is limited.
- If the internal changes of the product are complex, it may lead to the need to define many specific builder classes to implement such changes, resulting in a huge system. Therefore, in this case, it is necessary to consider whether to select the builder mode
4, Expand
In addition to the above purposes, the builder mode is also commonly used in development. When a class constructor needs to pass in many parameters, if an instance of this class is created, the code readability will be very poor, and it is easy to introduce errors. At this time, the builder mode can be used for reconstruction.
This is very common.
Before code refactoring:
@Data @AllArgsConstructor @NoArgsConstructor public class Phone { private String cpu; private String screen; private String memory; private String mainboard; } public class Client { public static void main(String[] args) { //Building Phone objects Phone phone = new Phone("intel","Samsung screen","Kingston","ASUS"); System.out.println(phone); } }
The new object needs to pass four parameters. What if there are more parameters? The readability of the code and the cost of using it are relatively high.
After code refactoring:
public class Phone { private String cpu; private String screen; private String memory; private String mainboard; private Phone(Builder builder) { cpu = builder.cpu; screen = builder.screen; memory = builder.memory; mainboard = builder.mainboard; } public static final class Builder { private String cpu; private String screen; private String memory; private String mainboard; public Builder() {} public Builder cpu(String val) { cpu = val; return this; } public Builder screen(String val) { screen = val; return this; } public Builder memory(String val) { memory = val; return this; } public Builder mainboard(String val) { mainboard = val; return this; } public Phone build() { return new Phone(this);} } @Override public String toString() { return "Phone{" + "cpu='" + cpu + '\'' + ", screen='" + screen + '\'' + ", memory='" + memory + '\'' + ", mainboard='" + mainboard + '\'' + '}'; } } public class Client { public static void main(String[] args) { Phone phone = new Phone.Builder() .cpu("intel") .mainboard("ASUS") .memory("Kingston") .screen("Samsung") .build(); System.out.println(phone); } }
You can often see the reconstructed code, but this is just a small demo for demonstration. There are many shortcomings. Please forgive me.
5, Factory mode VS builder mode
Java design pattern - Factory Method Pattern
1. Factory method mode VS builder mode
-
The factory method pattern focuses on the creation of the overall object;
-
The builder pattern focuses on the process of component construction, which is intended to create a complex object through precise construction step by step.
A simple example:
1. If you want to create a superman, if you use the factory method mode, you will directly produce a Superman with infinite power, flying and wearing underwear;
2. If you use the builder mode, you need to assemble the hands, head, feet, trunk and other parts, and then wear your underwear outside, so a superman was born.
2. Abstract factory pattern VS builder pattern
-
Abstract factory mode realizes the creation of product families. A product family is a series of products: product combinations with different classification dimensions. Adopting abstract factory mode does not need to care about the construction process, but only about what products are produced by what factory.
-
The builder model requires the product to be built according to the specified blueprint. Its main purpose is to produce a new product by assembling spare parts.
If the abstract factory pattern is regarded as an auto parts production factory to produce the products of a product family, the builder pattern is an auto assembly factory, which can return a complete car through the assembly of parts.
5, Talk to yourself
You roll me roll, everyone roll, when will this road be the end. 😇 (let's go straight to heaven)
Sometimes I want to stop and have a rest. It's hard to stick to one thing all the time. 😁
Hello, if you happen to see this article and think it's good for you, give it a praise and let me feel the joy of sharing, crab. 🤗
If there is something wrong, please don't be stingy!!
Similarly, if there is any doubt, please leave a message or private letter, and we will reply you as soon as possible.
Continuous updating