Class can provide a static method that returns a static instance of a class, such as a static method that obtains an instance of a Boolean wrapper class
1 Public Static Boolean ValueOf (boolean b) {2 return (b? True:false); 3 }
Advantages:
1, there is a name. When a class requires more than one constructor with the same signature, the static factory method is used instead of the constructor, and the name is carefully chosen to highlight the difference between them. such as: biginteger.probableprime (int bitlength, random rnd) returns a random prime number.
2, you do not have to create a new object each time they are called.
3. It is possible to return its subclasses, with greater flexibility in choosing the class that returns the object.
4, simplify the code.
Disadvantages:
1, the whole class if there is no public or protected type of the constructor, it will not be inherited, that is, not as a superclass, equivalent to final.
2, unlike other static methods in the API documentation is not different, unlike the constructor can be identified in the API
Static Factory method Customary name:
- The instance returned by valueof--has the same value as its parameter, which is actually a type conversion method
- Of--valueof Simple alternative, enumset in use
- GetInstance
- newinstance--with getinstance to ensure that each returned instance is different from other instances
- Gettype--type indicates the type of object returned by the factory method
- NewType
"Effective Java reading notes" Creating and destroying Objects (i): Consider using static factory methods instead of constructors