一、前言
《Effective Java》读书笔记系列
第二章 第1条:创建和销毁对象
二、介绍
通常情况下客户端想要获取一个类A
的实例,最传统的方式就是让A
提供一个public
的构造函数。实际上除此之外还有一种方式,那就是提供一个public
的静态工厂方法
三、举例
以Integer
为例子,Integer
里面除了提供构造函数外,还提供了对应的静态工厂方法
:
public final class Integer extends Number implements Comparable<Integer> {
//构造函数1
public Integer(int value) {
this.value = value;
}
//构造函数2
public Integer(String s) throws NumberFormatException {
this.value = parseInt(s, 10);
}
//静态工厂1
public static Integer valueOf(String s, int radix)
throws NumberFormatException {
return Integer.valueOf(parseInt(s,radix));
}
//静态工厂2
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}
//静态工厂3
public static Integer valueOf(int i