Effective Java --- study notes

I. static factory method in place of the constructor

We work to create an object the most common way is through the constructor, the book proposes to create objects using a static factory method it is also a good way.

Static factory method : Returns the class instance (object) static methods (static methods, the method return value is an instance of the target class)

 

1 public static Boolean valueOf(boolean b) {
2     return (b ? TRUE : FALSE);
3 }

 

Class can provide examples rather than by the class constructor external calls, using several advantages static factory method via static factory method External:

  1. static factory method has a name, the name of the constructor parameters are the same only different signatures: static factory method can be distinguished by naming API, and constructor parameters can only be distinguished by the API signature, by comparison method name can be more clear and straightforward expression API. There are two such parameters as constructor signatures, you can only change the order of the parameters to distinguish them.

  2. static factory methods do not have to create a new object each call: Each new out by the constructors of a new object is like, who often create the same situation and create high costs using a static factory method can return each the same object, which greatly improve performance. The above Boolean.valueOf every time is to return Boolean.TRUE or Boolean.FALSE. Because Boolean objects are immutable, so it makes sense instance require only Boolean.TRUE and Boolean.FALSE will be able to represent all instances of objects, and Boolean.TRUE and Boolean.FALSE the value can not be changed. There is no fear objects A and B also references Boolean.TRUE, but due to changes in the value of Boolean.TRUE object A and object B have an impact on, as is the Boolean immutable object, which itself can not be changed value .

  Suppose only just obtained and returned by the same object are static factory method for immutable objects, then only need to be able to determine whether the object == same without using equals.

 

Guess you like

Origin www.cnblogs.com/yhcjhun/p/10965979.html