码迷,mamicode.com
首页 > 编程语言 > 详细

Effective Java - Creating and Destroying Objects (1)

时间:2017-10-16 11:14:31      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:stat   bit   factory   blank   random   when   pos   target   targe   

Static Factory Methods v.s. Constructor

Advantages to use Static Factory Methods

1. More descriptive - the name of the factory methods can explain more than a constructor

  e.g. BigInteger.probablePrime(int bitLength, Random rnd) v.s. BigInteger(int bitLength, int certainty, Random rnd)

2. Can have multiple static factory methods for separate purpose

3. Static factory methods can return existing instance instead of generate a new one everytime when it‘s invoked

  - Good for immutable, singleton, uninstantiable

  - Improve performance

  e.g. Boolean.valueOf(boolean b)

4. Static factory method can return any subtype of their return type

  - an API can return objects without making their classes public (can only make the interface public)

5. Static factory method can help guess type parameter

      e.g. Map<String, List<String>> m = HashMap.newInstance();

 

Disadvantages when only provide static factory method

1. Classes without Public/Protected constructor cannot be subclassed.

2. Not readily distinguishable from other static methods

Effective Java - Creating and Destroying Objects (1)

标签:stat   bit   factory   blank   random   when   pos   target   targe   

原文地址:http://www.cnblogs.com/joycelee/p/7625508.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!