Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The Builder pattern of messing with Java Design pattern

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/03 Report--

The original site of the blog post: the builder pattern of the Java design pattern

Builder model

Separate the construction of a complex object from its representation, allowing the same construction process to create various representations.

Separate the construction of complex objects from their representation, allowing the same construction process to be used to create different representations. The popular point is that the process of creating an object is very complex, and we extract each of its elements from the creation process, and unused objects can be constructed through the same construction process. I don't know yet. You can see the following UML diagram.

Builder mode UML diagram

Cdn.xitu.io/2019/4/15/16a1ea2ba7ee7824?w=1080&h=1145&f=jpeg&s=130365 ">

This AbstractPersonBuilder is the same construction as above, and the different representation is that the PersonOneBuilder and PersonTwoBuilder here are two constructors in the same way, but the specific implementation is different and constructs a different representation. So it is the same construction process to construct different objects.

Builder model role

Abstract builder (AbstractPersonBuilder or Builder): abstract classes or interfaces, abstract methods of properties of complex objects that do not involve the creation of specific object parts

Concrete builders (PersonOneBuilder and PersonTwoBuilder): implement abstract builders that specify the creation of parts of complex objects for different businesses. Provide an example of the product after the construction process is completed

Director: call the specific builder to create each part of the complex object. The instructor does not involve specific product information, but is only responsible for ensuring that each part of the object is created completely or in a certain order.

Specific product (Person): complex objects to be created

Builder mode source code practical information

Source address: please click on me

Here I will talk about the builder pattern in three cases, the first is our most primitive builder pattern, the second is what we use in entity objects, and the third is that we usually use lombok in the most routine way of using entity objects.

The first builder model

The way the above is built according to the role is really used, which is slightly more responsible than the following two methods.

Abstract builder

Public abstract class AbstractPersonBuilder {protected Person product = new Person (); public abstract void buildName (); public abstract void buildAge (); public abstract void buildChildren (); public Person build () {return product;}}

The first specific builder

Public class PersonOneBuilder extends AbstractPersonBuilder {public void buildName () {product.setName ("old one");} public void buildAge () {product.setAge (44);} public void buildChildren () {product.setChildren (Lists.newArrayList ("little one"));}}

The second specific builder

Public class PersonTwoBuilder extends AbstractPersonBuilder {public void buildName () {product.setName ("old two");} public void buildAge () {product.setAge (55);} public void buildChildren () {product.setChildren (Lists.newArrayList ("little two"));}}

The Person class acts as product data

Public class Person {private String name; private int age; private List children; @ Override public String toString () {return "Person {" + "name='" + name +'\''+ ", age=" + age + ", children=" + children +'}';} public String getName () {return name } public void setName (String name) {this.name = name;} public int getAge () {return age;} public void setAge (int age) {this.age = age;} public List getChildren () {return children;} public void setChildren (List children) {this.children = children;}}

A commander who specifies a specific builder to build the object.

Public class Director {private AbstractPersonBuilder builder; public Director (AbstractPersonBuilder builder) {this.builder = builder;} public void setBuilder (AbstractPersonBuilder builder) {this.builder = builder;} public Person construct () {builder.buildName (); builder.buildAge (); builder.buildChildren (); return builder.build ();}}

Example

@ Slf4jpublic class Application {public static void main (String [] args) {Director director = new Director (new PersonOneBuilder ()); Person person = director.construct (); log.info ("person Information: {}", person); director.setBuilder (new PersonTwoBuilder ()); person = director.construct (); log.info ("person Information: {}", person);}}

Results:

The second builder model

The second approach is simpler than the one above, because we only specify one construction method, and we can also borrow a third-party tool, IDEA+Plugins.

You can search in IDEA

How to use it:

1. Find the class that needs to add bulid and automatically generate shortcut keys to view the build.

two。 According to your own style, you can define the name of bulid, the prefix of each bulid method and the package name. The specific bulider is shown in the following code.

PersonBuilder is used by the builder of Person

Public final class PersonBuilder {private String name; private int age; private List children; private PersonBuilder () {} public static PersonBuilder builder () {return new PersonBuilder ();} public PersonBuilder withName (String name) {this.name = name; return this;} public PersonBuilder withAge (int age) {this.age = age; return this } public PersonBuilder withChildren (List children) {this.children = children; return this;} public Person build () {Person person = new Person (); person.setName (name); person.setAge (age); person.setChildren (children); return person;}}

The Person class acts as product data

Public class Person {private String name; private int age; private List children; @ Override public String toString () {return "Person {" + "name='" + name +'\''+ ", age=" + age + ", children=" + children +'}';} public String getName () {return name } public void setName (String name) {this.name = name;} public int getAge () {return age;} public void setAge (int age) {this.age = age;} public List getChildren () {return children;} public void setChildren (List children) {this.children = children;}}

Example

@ Slf4jpublic class Application {public static void main (String [] args) {Person wang = PersonBuilder.builder () .withAge (40) .withChildren (Lists.newArrayList ("Li Yi", "Wu Lao San") .build (); log.info ("Lao Wang's message: {}", wang);}}

The results are as follows:

The third builder model

The third mode is relatively simple and much simpler, because we are borrowing lombok's @ Builder annotation. Lombok introduced the @ SuperBulider annotation in version 18.2 to solve the problem that the inheritance of the @ Builder class does not take effect. See the template method pattern of Java design pattern in my last article.

@ Data@Builder@NoArgsConstructor@AllArgsConstructorpublic class Person {private String name; private int age; private List children;} @ Slf4jpublic class Application {public static void main (String [] args) {Person wang = Person.builder () .age (40) .name ("Lao Wang") .children (Lists.newArrayList ("Li Yi Yi", "Wu Lao San") .build () Log.info ("Lao Wang's message: {}", wang);}}

Results:

Summary

The second and third modes are often defined in this way when we often manipulate objects such as VO, DO, and DTO. The first standard builder model, in fact, the role of the commander itself does not care about the specific product implementation, as opposed to a kind of decoupling, if a new builder is implemented, it can be easily expanded, in line with the opening and closing principle, but coincidentally, after the realization of the above advantages, but the disadvantages also follow, many new categories, high maintenance costs, if the builder changes internally. It's not very suitable for the builder model. In general, there are a lot of usage scenarios. Like StringBulider is actually a kind of. Like the RedisCacheManagerBuilder defined in this article that extends the ttl and key names of the redis cache in spring-boot 's spring-cache, and the Builder of Feign that we often talk about later, and so on.

Welcome to follow us.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report