This is the first piece of advice effective Java 2nd proposed:
Consider replacing constructors with static factory methods
The static factory method here is not a design pattern, mainly refers to static methods of statically modified, the description of static can refer to the previous blog post, "Final and Static in Java use scenario summary."
What is a static factory method?
Examples of reference books (excerpt from JDK1.7 Java.lang.Boolean)
Public final class Boolean implements java.io.Serializable, comparable<boolean> {public static Final Boolean true = new Boolean (true); public static Final Boolean false = new Boolean (false); public static Boolean valueOf (Boolean b) { return (b? True:false); }}
If you need to get a Boolean object, the general method is new Boolean(true) , but it can also be as shown Boolean.valueOf(true) , which is the static factory method.
Advantages of the Static factory approach
The first big advantage of static factory methods differs from constructors is that they have names .
When constructing an object using a constructor, we need to carefully compare the object to what kind of argument is passed through the document. However, static factory methods can use different method names to make the objects they construct more explicit. We can clearly understand what kind of object is constructed by the method name.
For example, the following example (excerpt from JDK1.7 Java.math.BigInteger)
public class BigInteger extends number implements comparable<biginteger> { /** * Returns a positive Big The Integer is probably prime, with the * specified bitlength. The probability a BigInteger returned * by this method is composite does not exceed 2<sup>-100</sup>. * /public static BigInteger probableprime (int bitlength, Random Rnd) { //XXX }}
The second big advantage of static factory methods differs from constructors is that you do not have to create a new object each time you call them .
We call the static factory method to return an object that might be cached, not a new object. Can be reused to avoid creating unnecessary duplicate objects.
If a program frequently requests the creation of the same objects, and the cost of creating them is high, the static factory approach can greatly improve performance.
This technique is illustrated in the preceding paragraph Boolean.valueOf(boolean) .
The third big advantage of static factory methods differs from constructors is that they can return objects of any subtype of the original return type.
We have more flexibility in choosing the classes that return objects. See Java.util.EnumSet, which itself is an abstract modification and cannot call its constructor directly. However, it is possible to call its static method noneOf to create the object, and return the appropriate object based on the parameter.
Public abstract class Enumset<e extends Enum<e>> extends abstractset<e> implements cloneable , java.io.Serializable { enumset (class<e>ElementType, enum[] universe) { } // Regularenumset and Jumboenumset are Enumset's subclass public static <e extends enum<e>> enumset<e> noneof ( Class<e> elementtype) { if (universe.length <=) return new regularenumset<> (ElementType, universe); else return new jumboenumset<>(ElementType, Universe);}}
The fourth big advantage is that you can make your code more concise when you create a parameterized type instance.
For example HashMap , instantiate:
General instantiation Mode map<string, list<string>> m = new hashmap<string, list<string>>();p ublic Static <k, v> hashmap<k, v> newinstance () { return new hashmap<k, v>();} Instantiate using a static factory method, simplifying cumbersome declarations map<string, list<string>> m = hashmap.newinstance ();
Disadvantages of the static factory approach
A class cannot be instantiated if it does not contain a public or protected constructor.
If we set the constructor to private in the class and only provide a static factory method to build the object, we will not be able to extend the class through inheritance.
But it also encourages us to extend classes using compositing rather than inheritance.
They are not actually any different from other static methods.
In the API documentation, static factory methods for building objects are not explicitly identified as constructors, and cannot be easily distinguished from other static methods.
If you only provide a static factory method instead of a constructor in a class, it can be difficult to find out how to instantiate a class.
We can compensate for this disadvantage by following the naming conventions of static factory methods:
- ValueOf-The returned instance has the same value as its argument and is generally used as a type conversion, for example
Boolean.valueOf(boolean)
- A more concise alternative to of-valueof.
- GetInstance-The returned instance is described by the parameters of the method, but cannot be said to have the same value as the parameter. For Singleton, use the parameterless getinstance to return a unique instance.
- Newinstance-like getinstance, but it ensures that new objects are returned every time.
- GetType-like getinstance, but the object returned by this method is another different class.
- NewType-like GetType, but returns a new object each time.
In summary, static factory methods and public constructors have their own uses, but static factory methods are usually more appropriate, so we should prioritize static factory methods.
Effective Java reading notes (i): Replacing constructors with static factory methods