考虑用静态工厂代替构造器

静态工厂是一个返回类的实例的静态方法。例如:

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

该方法根据给定的参数返回一个Boolean对象,但是需要注意的一点是。如果提供的参数相同的话获得的是同一个对象。

例如:

Boolean b1=Boolean.valueOf(true);
Boolean b2=Boolean.valueOf(true);
System.out.println(b1==b2);
Boolean b3=new Boolean(true);
Boolean b4=new Boolean(true);
System.out.println(b3==b4);

结果就为true false

静态工厂方法的优势:

1 有名称,使用起来更明确

2 不必在每次调用的时候都创建一个对象。可以预先创建好对象,重复利用。

3 可以返回原类型的任何子类型对象

4 可以用更简洁的代码创建复杂对象

例如 Map<String ,List<String>> m=new Map<String ,List<String>>();

使用静态工厂方法就可以这样:

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

return new HashMap<K,V>();

}

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

缺点:

1 类不包含共有的或者受保护的构造器,就不能被子类化。虽然这是个缺点,但是无法使用继承也是被鼓励的,应该尽量使用组合来代替继承。

2 跟其他的静态方法没有区别,不易于在API文档中查找。

原文地址:https://www.cnblogs.com/macula7/p/1960644.html