一、Item 1
Consider static factory methods instead of constructors(考虑用静态工厂方法代替构造函数)
例:Boolean 类提供了将boolean基本类型转换为Boolean实例的方法
/**
* The {@code Boolean} object corresponding to the primitive
* value {@code true}.
*/
public static final Boolean TRUE = new Boolean(true);
/**
* The {@code Boolean} object corresponding to the primitive
* value {@code false}.
*/
public static final Boolean FALSE = new Boolean(false);
/**
* Returns a {@code Boolean} instance representing the specified
* {@code boolean} value. If the specified {@code boolean} value
* is {@code true}, this method returns {@code Boolean.TRUE};
* if it is {@code false}, this method returns {@code Boolean.FALSE}.
* If a new {@code Boolean} instance is not required, this method
* should generally be used in preference to the constructor
* {@link #Boolean(boolean)}, as this method is likely to yield
* significantly better space and time performance.
*
* @param b a boolean value.
* @return a {@code Boolean} instance representing {@code b}.
* @since 1.4
*/
public static Boolean valueOf(boolean b) {
return (b ? TRUE : FALSE);
}
静态工厂方法的优点
- 静态工厂方法与构造函数相比的第一个优点:静态工厂方法有确切名称 如果构造函数的参数本身不能描述返回的对象,有确切名称的静态工厂方法更容易使用,代码更容易阅读
- 静态工厂方法不需要再每次调用时都创建新的对象 其使用预先构造好的实例,或者在构造实例时缓存实例,重复分配这些实例以避免创建不必要的重复对象
- 可以通过静态工厂方法获取返回类型的任何子类的对象 这对于选择返回对象的类提供了很大的灵活性
- 返回对象的类可以随调用的不同而变化,作为输入参数的函数
- 在编写包含方法的类时,返回对象的类不需要存在 这种灵活的静态方法构成了服务提供框架的基础,比如java数据库连接JDBC 服务提供者框架是一个系统,其中提供者实现一个服务,客户端可以使用这些实现,从而将客户端与实现分离
静态工厂方法的缺点
- 没有public或protected的构造函数的类不能被子类化
- 静态工厂方法很难被程序员发现 其在javadoc工具 导出的 API接口文档中没有构造函数那么明显