[Code optimization] builder mode is used when there are many parameters in the constructor.
Source: Internet
Author: User
Static factory and constructor have a common limitation: Neither can be well extended to a large number of optional parameters.
1. For constructors with multiple optional parameters, we are used to the overlapping constructor mode. For example, a parameter constructor calls the constructor with two parameters,The constructor of the two parameters calls the three parameters, and so on.Public class user {
Private int ID; private string name; private string age; private string sex; public user (int id) {This (ID, null );}
Public user (int id, string name) {This (ID, name, null);} public user (int id, string name, string age) {This (ID, name, age, null );}
}
When there are enough parameters, this overlapping call mode is hard to write and difficult to read.
2. Use the JavaBean mode instead of the method. You only need to call a non-argument constructor to create an object and then call the setter method to set each required parameter.
Public class user {
Private int ID; private string name; private string age; private string sex; public user () {}// setters public void setid (INT value) {id = value ;} public void setname (string value) {name = value;} public void setage (string value) {age = value;} public void setsex (string value) {sex = value ;}
}
This JavaBean pattern makes up for the tedious calling of the overlapping constructor. However, it is a pity that the JavaBean has its own serious disadvantages: the constructor may be divided into several constructor javans, which may be inconsistent, that is, the thread security cannot be guaranteed.
3. The third alternative method can be as secure as the overlapping constructor, or as readable as the JavaBean. That is, the builder mode is used. Public class user {
Private int ID; private string name; private string age; private string sex; public user (Builder) {id = builder. ID; name = builder. name; age = builder. age; Sex = builder. sex;} public Builder (int id) {This. id = ID;} public builder setname (string Val) {This. name = val; return this;} public builder setage (string Val) {This. age = val; return this;} public builder setsex (string Val) {This. sex = val; return this ;}
}
In short, if the constructor or static factory has many parameters, using the builder mode is a good choice.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.