Effective java 笔记1

[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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值