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

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

好处:

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.他们与其他静态方法没有任何区别。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值