This blog is the Java Classic book "Effective Java (second Edition)" Reading notes, this book a total of 78 to write high-quality Java code Recommendations, I will try to explain it more easily, so the blog updates about 1 months.
1th: Consider replacing the constructor with a static factory method
In general, we use the class's constructor to instantiate it, which seems to be no doubt. But the "static factory approach" also requires our high degree of attention.
What is a "static factory method"? This differs from the factory method in design mode, which we can understand as "using a static method in a class to return an instance of this class", for example:
Public Static People getinstance () { returnnew people ();}
It is a "method", then it is different from the constructor, it can modify the method name at will, which brings the first advantage-there is a name . Sometimes the constructors of a class tend to be more than one, and their names are the same, except for arguments, and if different parameters bring different meanings, it is difficult for callers to understand what they mean in addition to annotations. For example, BigInteger (int, int, Random) returns a prime number, but it is difficult for callers to understand what the API designer wants to say, If you have Biginteger.probableprime static factory method At this time, you can clearly understand what the API designer wants to express. Example of a JDK: the Executors class, where there are static methods such as Newfixedthread, Newsinglethreadexecutor, Newcachedthreadpool, and so on, because they have a "name", All the more clearly understand the meaning of the API.
The second advantage of the static factory approach mentioned in effective Java is that you don't have to create an object repeatedly , which is actually a single-case pattern that is loaded or called a hungry man. For example:
Public class Instance () { privatestaticnew Instance (); Private Instance () {} Public Static Instance getinstance () { return Instance; }}
the third advantage of a static factory method is that it can return any subtype of the original return type . This sentence is not easy to understand, to cite a JDK example: collections class.
List List = Collections.synchronizedlist (new ArrayList ())
This example shows an object that can return any subtype of the original return type.
With regard to the fourth advantage of the static factory approach, when creating instances of parameterized types, they make the code more concise, and the book cited an example:
New Hashmap<string, list<string>> (); // It's going to be tedious .
After providing a static factory method to the collection class:
Public static <k, v> hashmap<k, v> newinstance () { returnnew hashmap< K, v>();}
But actually the collection class from JDK7 (including JDK7) can be replaced with the following concise code:
New Hashmap<> ();
The static factory method also has two drawbacks: one is that the non-public class returned by the public static method cannot be instantiated, That is to say, the synchronizedlist returned by Collections.synchronizedlist cannot be instantiated, and the other is that it is troublesome to find the API, which is not identified in the API as the ordinary class has a constructor, but as with other ordinary static methods, the book mentions several idiomatic names:
ValueOf
Of
GetInstance
Newinstance
GetType
NewType
2nd: Consider using the builder when you encounter multiple constructor parameters
Have you ever written a code like the following:
Public voidStudent () {/*must fill in*/ PrivateString name; Private intAge ; /*Optional Fill*/ PrivateString sex; PrivateString grade; PublicStudent (string name, string sex) { This(Name, sex, 0); } PublicStudent (string name, String sex,intAge ) { This(name, sex, Age, ""); } PublicStudent (string name, String sex,intAge , String grade) { This. Name =name; This. Sex =sex; This. Age =Age ; This. grade =grade; }}
When I want to instantiate a name called "Kevin", gender male, but do not write age, only grade "1 grade", this time code is: have to pass the value for age this parameter. If you add a class-only construction method, that will add a lot of code, and more seriously, if you do not have a detailed document or comment, it is very common to see so many construction methods will not do so.
New Student ("Kevin", "Male", "0", "1 Grade");
There is, of course, another way to construct a required item, while other options are passed using the setter method. For example:
New Student ("Kevin", "male"), Student.setgrade ("1 grade");
This actually causes the JavaBean to be in an inconsistent state during the construction process, which means that the instanced object is supposed to be one go, but now it is split into two big strides, which leads to its thread being unsafe and further triggering unpredictable consequences.
The book mentions that the "perfect" solution is to use the "builder mode", which allows you to view the builder mode for this design pattern. This solution is a form of the builder pattern, the core of which is not to directly generate the desired object, but rather let the client use all the necessary parameters call the constructor (or static factory), get a Builder object, and then call a setter-like method to set the relevant optional parameters . The builder mode is as follows:
/*** Builder Mode * Created by Yulinfeng on 2017/8/3.*/ Public classStudent {/*must fill in*/ PrivateString name; Private intAge ; /*Optional Fill*/ PrivateString sex; PrivateString grade; Public Static classBuilder {PrivateString name; Private intAge ; PrivateString sex = ""; PrivateString grade = ""; PublicBuilder (String name,intAge ) { This. Name =name; This. Age =Age ; } PublicBuilder sex (String sex) { This. Sex =sex; return This; } PublicBuilder Grade (String grade) { This. grade =grade; return This; } PublicStudent Build () {return NewStudent ( This); } } PrivateStudent (Builder builder) { This. Name =Builder.name; This. Age =Builder.age; This. Sex =Builder.sex; This. grade =Builder.grade; }}
Client code:
New Student.builder ("Kevin"). Grade ("1 grade"). Build ();
Such client-side code is easy to write, and easy to read. It is not easy to write the student class with the builder pattern for a bit of an understanding, even more code than an overlapping constructor. So when the optional arguments are many, use the overlay constructor sparingly and use the builder pattern instead.
--170803
Effective Java Popular Understanding (continuous update)