[size=medium]Effective Java 创建对象之 static factory method[/size]
1:优先考虑static factory method,然后再考虑constructor
1.1 static factory method 的优点
1.1.1 static factory method 相对constructor 更容易命名,尤其是当static factory method 和 constructor 方法数量多的时候,static factory method 容易命名的好处更加突出,更加容易理解方法的用途。
1.1.2 获取对象时,constructor每次都生成新的对象, 而static factory method却不需要
1.1.3 constructor只能返回当前类的对象,而static factory method 可以返回当前类的对象或 当前类的子类对象
1.1.4 创建泛型对象时,static factory method 可以减少所用的词(所使用语句的长度)
1.2 static factory method 的缺点
1.2.1 最大的缺点是:如果没有public或者protected constructor的类,该类无法被继承。
1.2.2 有时候多个static factory method 会让程序员迷惑,不知道使用哪个方法获取对象那个比较好
对于第二条,遵循以下规则就可以极大程度上减弱它的影响:
• valueOf—
Returns an instance that has, loosely speaking, the same value as its
parameters. Such static factories are effectively type-conversion methods.
• of—A concise alternative to valueOf, popularized by EnumSet
• getInstance—Returns an instance that is described by the parameters but
cannot be said to have the same value. In the case of a singleton, getInstance
takes no parameters and returns the sole instance.
• newInstance—Like getInstance, except that newInstance guarantees that
each instance returned is distinct from all others.
• getType—Like getInstance, but used when the factory method is in a different
class. Type indicates the type of object returned by the factory method.
• newType—Like newInstance, but used when the factory method is in a different
class. Type indicates the type of object returned by the factory method.
1:优先考虑static factory method,然后再考虑constructor
1.1 static factory method 的优点
1.1.1 static factory method 相对constructor 更容易命名,尤其是当static factory method 和 constructor 方法数量多的时候,static factory method 容易命名的好处更加突出,更加容易理解方法的用途。
1.1.2 获取对象时,constructor每次都生成新的对象, 而static factory method却不需要
1.1.3 constructor只能返回当前类的对象,而static factory method 可以返回当前类的对象或 当前类的子类对象
1.1.4 创建泛型对象时,static factory method 可以减少所用的词(所使用语句的长度)
1.2 static factory method 的缺点
1.2.1 最大的缺点是:如果没有public或者protected constructor的类,该类无法被继承。
1.2.2 有时候多个static factory method 会让程序员迷惑,不知道使用哪个方法获取对象那个比较好
对于第二条,遵循以下规则就可以极大程度上减弱它的影响:
• valueOf—
Returns an instance that has, loosely speaking, the same value as its
parameters. Such static factories are effectively type-conversion methods.
• of—A concise alternative to valueOf, popularized by EnumSet
• getInstance—Returns an instance that is described by the parameters but
cannot be said to have the same value. In the case of a singleton, getInstance
takes no parameters and returns the sole instance.
• newInstance—Like getInstance, except that newInstance guarantees that
each instance returned is distinct from all others.
• getType—Like getInstance, but used when the factory method is in a different
class. Type indicates the type of object returned by the factory method.
• newType—Like newInstance, but used when the factory method is in a different
class. Type indicates the type of object returned by the factory method.