Consider static factory methods instead of constructor

抄袭自《Effective Java ,Second Edition》

The normal way for a class to allow a client to obtain an instance of itself is to provide a public constructor. There is another technique that should be a part of every
programmer’s toolkit.


例子:Boolean类

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


One advantage of static factory methods is that, unlike constructors, they
have names.

A second advantage of static factory methods is that, unlike constructors,
they are not required to create a new object each time they’re invoked.

A third advantage of static factory methods is that, unlike constructors,
they can return an object of any subtype of their return type.

引用别人文章的一些东西

以下静态工厂方法的优势摘自http://blog.csdn.net/dm_vincent/article/details/8513720

静态工厂方法的优势

 

当然,这里所说的优势,通常都是和传统构造函数相比得到的。

 

静态工厂方法拥有名字

静态工厂方法拥有自己的名字,而构造函数则没有。这也就意味着,同一组参数列表,只能有唯一的一个构造函数(通过改变参数列表中参数的顺序,可以有多个构造函数,但是很明显,这不是一个好主意)。相比之下,静态工厂方法则没有这个限制,对同一组参数,可以有任意多的静态工厂方法。因此,这种情况下使用静态工厂方法来进行对象实例化更加灵活,可读性也更好。

 

对于对象实例化的更多控制

对于构造函数而言,一旦它被调用,那么就肯定会生成一个新的实例。而调用静态工厂方法则不一定,它只需要返回一个对象的实例就够了,至于这个返回的对象是如何得到的,它并不关注。因此,静态工厂方法对于对象的实例化就有了更多的控制权。它能够利用预先创建好的不可变对象(Immutable Instance),也能够从缓存中获取某个经常被请求的对象。从而大幅度的提高性能。

英文原文可参照

This
allows immutable classes (Item 15) to use preconstructed instances, or to cache
instances as they’re constructed, and dispense them repeatedly to avoid creating
unnecessary duplicate objects. The Boolean.valueOf(boolean)method illustrates this technique: it never creates an object. This technique is similar to the
Flyweightpattern [Gamma95, p. 195]. It can greatly improve performance if
equivalent objects are requested often, especially if they are expensive to create.

 

返回对象的类型更加泛化

对于构造函数而言,它只能返回当前类的实例。而静态工厂方法的实际返回类型可以是声明返回类型的任何子类型。比如,声明返回Base类型的静态工厂方法,实际上它能够返回Sub类型,只要SubBase的子类型。因为子类型的概念不仅限于继承层次,还可以适用在接口和其实现类之间,因此这种泛化的关系也非常契合“面向接口编程”这一指导原则。

转载于:https://my.oschina.net/liangzhenghui/blog/178187

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值