第1条:考虑用静态工厂方法替代构造器
Item 1:Consider static factory methods instead of constructors
Advantages:
1.One advantage of static factory methods is that,unlike constructors,they have names.
构造器只能以类名命名,而静态工厂方法可以有自己的名字。考虑如下两种情况:
a.使用BigInteger(int, int, Random)构建一个素数
b.构造器的参数类型相同但是顺序不同
构造方法名称只能是类名,此时是很难知道构造器要表达的意义以及各个构造器之间的区别,容易导致程序员误调。当使用静态工厂方法,就没有这些弊端,因为可以通过方法名称加以说明。
2.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.
通过静态工厂方法可以很好的控制类的实例,它可以实现实例的缓存、单例、不可实例化、实例不可变等功能。
3.A third advantage of static factory methods is that ,unlike constructors,they can return an object of any subtype of their return type.
可以返回其返回值类型的任何不同的子类并且强迫客户端面向接口编程.
4.A fourth advantage of static factory methods is that the class of returned object can vary from call to call as a function of the input parameters.
可以根据参数返回不同的实现,类似策略模式。
5.A fifth advantage of static factory motheds is that the class of returned object need not exist when then class containing the methed is written.
静态方法返回的类,在编写该静态方法的时候可以并不存在。
Shortcoming:
1.The main limitation of providing only static factory method is that classes without public or protected constructors cant not be subclassed.
只提供静态工厂方法,但是没有public或者protected的构造器,则类不能被继承。
2.A second shortcoming of static factory mothed is that they of hard for programmers to find.
不是所有人都习惯使用静态工厂方法创建对象。用静态工厂方法代替构造器,会使程序员花费一定时间去了解如何去实例化相应的对象。
常用静态工厂方法的命名方式:
• from—A type-conversion method that takes a single parameter and returns a
corresponding instance of this type, for example:
Date d = Date.from(instant);
• of—An aggregation method that takes multiple parameters and returns an instance of this type that incorporates them, for example:
Set faceCards = EnumSet.of(JACK, QUEEN, KING);
• valueOf—A more verbose alternative to from and of, for example:
BigInteger prime = BigInteger.valueOf(Integer.MAX_VALUE);
• instance or getInstance—Returns an instance that is described by its parameters (if any) but cannot be said to have the same value, for example:
StackWalker luke = StackWalker.getInstance(options);
• create or newInstance—Like instance or getInstance, except that the
method guarantees that each call returns a new instance, for example:
Object newArray = Array.newInstance(classObject, arrayLen);
• getType—Like getInstance, but used if the factory method is in a different class. Type is the type of object returned by the factory method, for example:
FileStore fs = Files.getFileStore(path);
• newType—Like newInstance, but used if the factory method is in a different class.Type is the type of object returned by the factory method, for example:
BufferedReader br = Files.newBufferedReader(path);
• type—A concise alternative to getType and newType, for example:
List litany = Collections.list(legacyLitany);