Effective Java - Item1

让对象的创建与销毁在掌控中。

Item 1: 使用静态工厂方法而非使用构造函数

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

优势:

1. 方法名+参数名,相较于构造函数,能更好的描述返回对象;

BigInteger(int, int, Random)
BigInteger.probablePrime(int, int, Random)

2. 不会像构造函数那样,每次调用不一定必须返回新对象;

  利用静态工厂方法可以得到类的单例对象,也可以辅助得到无法直接使用构造函数实例化的类的实例。

public class Singleton {

    private static Singleton instance = new Singleton();

    private Singleton(){
        //在类外部无法用私有构造函数实例化
    }

    public static Singleton getInstance(){
        return instance;
    }

    public static void main(String[] args) {
        //在类内部可以通过私有构造函数实例化
        Singleton instance = new Singleton();

        Singleton instance1 = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        //比较实例地址
        System.out.println(instance1 == instance2);
    }
}

3. 可以返回子类对象

猜你喜欢

转载自www.cnblogs.com/hello-yz/p/9811344.html