Effective Java - Creating and Destroying Objects (1)

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

转载于:https://www.cnblogs.com/joycelee/p/7625508.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值