java 静态工厂

来源:互联网 发布:雕铣机编程软件 编辑:程序博客网 时间:2024/05/03 08:13

public abstract class Foo {

//继承了Foo的类的集合

private static Map implementations = null;

    private static synchronized void initMapIfNecessary() {
if (null == implementations) {
implementations = new HashMap();
}
    }
    
            public static Foo getInstance(String key) {
initMaoIfNecessary();
Class c = (Class) implementations.get(key);
if(c == null)
return new DefaultFoo();
try {
return (Foo) c.newInstance();
} catch(Exception e) {
return new DefaultFoo();
}
    }
}
0 0