思考用静态工厂方法代替构造函数

考虑用静态工厂方法代替构造函数

考虑静态工厂代替构造函数:

好处:

1.静态工厂方法与构造函数不同,静态工厂方法具有名字。

2.与构造函数不同,他们每次被调用的时候,不要求非得创建一个新的对象。

3.他们可以返回一个原类型的子类型对象。

public abstract class Foo {

//Maps String key to corresponding Class object

private static Map implementations = null;

//Initalizes implementations map the first time it's called

private static synchronized void initMapIfNecessary(){

if(implementations == null){

implementations = new HashMap();

//Load implementations class names and keys from

//Properties file, translate names into Class

//objects using Class.forName and store mappings.

}

}

public static Foo getInstance(String key){

initMapIfNecessary();

Class c = (Class)implementations.get(key);

if(c == null){

//return new DefaultFoo();

}

try{

return (Foo)c.newInstance();

}catch(Exception e){

//return new DefaultFoo();

return null;

}

}

}

 

缺点:

1.类如果不含公有的或者受保护的构造函数,就不能被子类化。

2.他们与其他静态方法没有任何区别。