Builder mode_ Power node Java college sorting

Definition: separate the construction of a complex object from its representation, so that the same construction process can create different representations.

Type: create class schema

Class diagram:

Four elements

code implementation

Advantages of builder model

First, the builder pattern 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 director class can achieve better stability as a whole.

Second, the builder pattern is easy to extend. If there are new requirements, it can be completed by implementing a new builder class. Basically, there is no need to modify the previously tested code, so there will be no risk to the original functions.

Difference between builder mode and factory mode

We can see that the builder mode is very similar to the factory mode. In general, the builder mode only has one more role of "director" than the factory mode. In the class diagram of the builder pattern, if the director class is regarded as the client of the final call, the rest of the diagram can be regarded as a simple factory pattern.

Compared with factory mode, builder mode is generally used to create more complex objects. Because the creation process of objects is more complex, the creation process of objects is independent to form a new class - director class. In other words, the factory pattern encapsulates the whole creation process of objects in the factory class, and the factory class provides the final product to the client; In the builder mode, the builder class generally only provides the construction of each component in the product class, and delivers the specific construction process to the director class. The director class is responsible for building each component into a product according to specific rules, and then delivering the built product to the client.

summary

The builder mode is similar to the factory mode. They are both builder modes, and the applicable scenarios are also very similar. Generally speaking, if the product construction is very complex, please use the factory mode; If the construction of the product is more complex, please use the builder mode.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>