Effective Java——Item 1: Consider static factory methods instead of constructors

来源:互联网 发布:kc网络电话软件 编辑:程序博客网 时间:2024/05/21 11:25
 Item 1: Consider static factory methods instead of constructors

考虑用静态的工厂方法来代替构造函数

 

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.

好处之二是,不像构造函数每次调用创造出一个新的对象,静态的工厂方法并不是必须返回一个新的对象。

 

利用这一特点,静态工厂方法可用来创建以下类的实例:

1)单例(Singleton)类:只有惟一的实例的类。比如说加载配置文件

把构造方法定义为private类型,提供public static类型的静态工厂方法,例如:

public class GlobalConfig {

private static final GlobalConfig INSTANCE =new GlobalConfig();

private GlobalConfig() {…}

public static GlobalConfig getInstance(){return INSTANCE;}

}

 

2)枚举类:实例的数量有限的类。

枚举类是指实例的数目有限的类,比如表示性别的Gender类,它只有两个实例:Gender.FEMALEGender.MALE。在创建枚举类时,可以考虑采用以下设计模式:
1)
把构造方法定义为private类型。
2)
提供一些public static final类型的静态变量,每个静态变量引用类的一个实例。
3)
如果需要的话,提供静态工厂方法,允许用户根据特定参数获得与之匹配的实例。

 

A third advantage of static factory methods is that, unlike constructors,

they can return an object of any subtype of their return type.

好处之三是,不像构造函数只能返回本类型的实例,静态工厂方法可以返回子类型的对象实例。

这个特性可以应用于实现松耦合的接口

public static Shape getShape(int type){…}

以上方法声明的返回类型是Shape类型,实际上返回的是Shape子类的实例。对于Shape类的使用者Panel类,只用访问Shape类,而不必访问它的子类:

//获得一个Circle实例
Shape shape=ShapeFactory.getInstance(ShapeFactory.SHAPE_TYPE_CIRCLE);

A fourth advantage of static factory methods is that they reduce the verbosity

of creating parameterized type instances.

好处之四是,静态工厂方法可以替代有着冗长的参数列表的构造函数。

Map<String, List<String>> m =

new HashMap<String, List<String>>();

可以被以下静态工厂方法替代

public static <K, V> HashMap<K, V> newInstance() {

return new HashMap<K, V>();

}

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

 

The main disadvantage of providing only static factory methods is that

classes without public or protected constructors cannot be subclassed.

害处之一是,如果只提供静态工厂类方法而不提供public或者protected的构造函数,那么这个类将不能被子类化

 

A second disadvantage of static factory methods is that they are not

readily distinguishable from other static methods.

害处之二是,静态工厂方法不能很明显的和其他静态方法区别开来

 

以下是一些常用的静态工厂方法名称:

valueOf ——类型转换

of ——valueOf()的简明写法

getInstance ——返回实例

newInstance ——返回一个新的实例

getType ——返回一个对象,不是和该类同一类型

newType ——返回一个新的对象