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

How to use the builder pattern when the constructor has too many parameters

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article will explain in detail how to use the builder pattern when there are too many parameters in the construction method. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.

I. the shortcomings of the traditional way

1. Scalable construction method

The scalable construction method is the most common one we usually write, please take a look at the following code

Public class Student {private int id; / / necessary private String name;// necessary private int age; / / optional private int sclass; / / optional private int height;// optional private float weight;// optional private float score;// optional / / constructor 1: default constructor public Student () {}; / / constructor 2: necessary field constructor public Student (int id, String name) {this.id = id This.name = name;} / / Construction method 3: all field construction methods public Student (int id, String name, int age, int sclass, int height, float weight, float score) {super (); this.id = id; this.name = name; this.age = age; this.sclass = sclass; this.height = height; this.weight = weight; this.score = score;}}

If we are going to create a Student class, usually like this, take a look at the following code:

Public class Main {public static void main (String [] args) {/ / 1, scalable construction method Student student1 = new Student (); Student student2 = new Student (1, "Yu Gong wants to move the mountain"); Student student3 = new Student (2, "Yu Gong wants to move the mountain", 18meme 175J 120jue 99);}}

Now that we have given an example of seven fields, which is easier to understand, let's analyze its shortcomings:

Disadvantage 1: reverse the field, the compiler will not report an error

For example, there is a weight and a score in the above field, both of which are of type float. If you new a Student class and accidentally write it upside down, the compiler will not notice it.

Disadvantage 2: difficult to understand

There are only seven fields here, and if there are more than a dozen, we need to keep going to the Student class to see what the first parameter should write. Users can't understand what each field property represents when they see this Student (2).

Disadvantage 3: you have to set a value if you don't want to set a parameter.

Sometimes our Student just wants to set the ID, name, and age fields, and the rest doesn't matter, but in this mode you have to set all the property values.

Since there are these shortcomings above, we may think of another way, and that is javaBean.

2. JavaBean mode

Let's first look at how the javaBean mode is written.

Public class Student {private int id; / / necessary private String name;// necessary private int age; / / optional private int sclass; / / optional private int height;// optional private float weight;// optional private float score;// optional / / constructor 1: default constructor public Student () {} / / getter and setter method public int getId () {return id;} public void setId (int id) {this.id = id } 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 int getSclass () {return sclass;} public void setSclass (int sclass) {this.sclass = sclass;} public int getHeight () {return height;} public void setHeight (int height) {this.height = height;} public float getWeight () {return weight } public void setWeight (float weight) {this.weight = weight;} public float getScore () {return score;} public void setScore (float score) {this.score = score;};}

This mode looks comfortable, except that the corresponding getter and setter methods are set. Let's take a look at how to new a Student class in this way.

Public class Main {public static void main (String [] args) {/ / 2, javaBean mode Student student1 = new Student (); student1.setId (1); student1.setName ("Yu Gong wants to move mountains"); student1.setSclass (1); student1.setWeight (180); student1.setHeight; student1.setScore (100); student1.setAge (20);}}

It looks okay, but I just typed it out one by one. Actually know when using the same disgusting, now to sum up a wave of his shortcomings.

Disadvantage 1: JavaBean may be in an inconsistent state during construction

The JavaBeans pattern itself has serious flaws. Because the constructor is segmented in multiple calls, the JavaBean may be in an inconsistent state during the construction process. This class does not have the option to perform consistency by checking the validity of the construction parameter parameters. Trying to use an object in an inconsistent state can lead to errors that are very different from the code that contains bug, so it is difficult to debug.

To talk about my understanding of it, in the above example, our student1 object is called the set method multiple times, but sometimes when using this bean, the remaining setter methods are not finished, so when called again, we find that the same javaBean presents two states. So it is in an inconsistent state.

Disadvantage 2: unable to guarantee the immutability of javaBean

The variability is not changed after instantiation using the first schema scalable construction method, and all the data is determined. Thread safety can also be guaranteed. However, if the setter method is provided, there is no guarantee. For example:

Public class Main {public static void main (String [] args) {/ / 2, javaBean mode Student student1 = new Student (); student1.setId (1); student1.setName ("Yu Gong wants to move mountains"); student1.setSclass (1); student1.setWeight (180); student1.setHeight (175,100); student1.setAge (20); System.out.println (student1.getName ()); student1.setName ("Feng Dongdong") System.out.println (student1.getName ());}} / / output result: Yu Gong wants to move the mountain, Feng Dongdong

As you can see, we can set name on the Student object multiple times, which is inconsistent.

Since there are all kinds of problems in the first two kinds. Now let's take a look at today's theme builder mode.

II. Builder mode

As usual, let's take a look at what the builder pattern looks like. Let's analyze his strengths and weaknesses again.

Public class Student {private int id; / / necessary private String name;// necessary private int age; / / optional private int sclass; / / optional private int height;// optional private float weight;// optional private float score;// optional public Student (Builder builder) {this.id = builder.id; this.name = builder.name; this.age = builder.age; this.sclass = builder.sclass; this.height = builder.height This.weight = builder.weight; this.score = builder.score;} public static class Builder {private int id; / / necessary private String name;// necessary private int age; / / optional private int sclass; / / optional private int height;// optional private float weight;// optional private float score / / optional / / Construction method for required parameters public Builder (int id, String name) {this.id = id; this.name = name;} public Builder setId (int id) {this.id = id; return this;} public Builder setName (String name) {this.name = name; return this;} public Builder setAge (int age) {this.age = age; return this } public Builder setSclass (int sclass) {this.sclass = sclass; return this;} public Builder setHeight (int height) {this.height = height; return this;} public Builder setWeight (float weight) {this.weight = weight; return this;} public Builder setScore (float score) {this.score = score; return this } / / external public Student build () {return new Student (this);}

The above code constructs a Builder class internally, and then we'll see how to use it.

Public class Main {public static void main (String [] args) {/ / 3, Builder mode Student stu = new Student.Builder (1, "Yu Gong wants to move mountains") .setAge (20) .setHeight (175) .setSclass (1) .setScore (100) .setWeight (100). Build ();}}

Its shortcomings are also introduced in this book, and it is intuitive to see that the amount of code in the Student class has increased a lot. But the Student class, which we only need to write once, makes it convenient for us to create objects.

Advantage 1: there is no reversal field

As you can see above, each time a new field value is added, it is done through set. It has the advantages of javaBean.

Advantage 2: flexible construction parameters

As soon as we write the necessary fields, we can choose whether or not to set those non-essential fields.

Advantage 3: there is no inconsistent state

With builder mode, the creation of an object must wait until the build is complete.

Advantage 4: flexible use

A single builder can be reused to build multiple objects. The parameters of the builder can be adjusted between calls to the build method to change the object created. Builder can automatically populate some properties when creating an object, such as the sequence number increased each time the object is created.

Disadvantages:

In order to create an object, you must first create its builder. Although the cost of creating this builder is unlikely to be noticed in practice, problems can arise in cases where performance is critical. Moreover, the builder pattern is more verbose than the scalable constructor pattern, so it is worth using only if you have enough parameters, such as four or more.

However, if you start with constructors or static factories and switch to builder, outdated constructors or static factories face an awkward situation when the class evolves to get out of control of the number of parameters. Therefore, it is best to create a builder from the beginning.

When there are too many parameters of the construction method, how to use the builder pattern is shared here. I hope the above content can be helpful to everyone and learn more knowledge. If you think the article is good, you can share it for more people to see.

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

Development

Wechat

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

12
Report