java没有elseif,在Java中创建一个不依赖于if-else的工厂方法

博客探讨了如何避免在Java代码中使用大量if-else语句,提出通过工厂方法和映射来实现更优雅的解决方案。作者创建了一个接口AnimalFactory和一个静态工厂映射,将字符串与动物类关联起来,简化了根据字符串创建对象的过程。当类列表增加时,这种方法更加灵活且易于维护。
摘要由CSDN通过智能技术生成

Currently I have a method that acts as a factory based on a given String.

For example:

public Animal createAnimal(String action)

{

if (action.equals("Meow"))

{

return new Cat();

}

else if (action.equals("Woof"))

{

return new Dog();

}

...

etc.

}

What I want to do is avoid the entire if-else issue when the list of classes grows.

I figure I need to have two methods, one that registers Strings to classes and another that returns the class based on the String of the action.

What's a nice way to do this in Java?

解决方案

What you've done is probably the best way to go about it, until a switch on string is available.

You could create factory objects and a map from strings to these. But this does get a tad verbose in current Java.

private interface AnimalFactory {

Animal create();

}

private static final Map factoryMap =

Collections.unmodifiableMap(new HashMap() {{

put("Meow", new AnimalFactory() { public Animal create() { return new Cat(); }});

put("Woof", new AnimalFactory() { public Animal create() { return new Dog(); }});

}});

public Animal createAnimal(String action) {

AnimalFactory factory = factoryMap.get(action);

if (factory == null) {

throw new EhException();

}

return factory.create();

}

At the time this answer was originally written, the features intended for JDK7 could make the code look as below. As it turned out, lambdas appeared in Java SE 8 and, as far as I am aware, there are no plans for map literals.

private interface AnimalFactory {

Animal create();

}

private static final Map factoryMap = {

"Meow" : { -> new Cat() },

"Woof" : { -> new Dog() },

};

public Animal createAnimal(String action) {

AnimalFactory factory = factoryMap.get(action);

if (factory == null) {

throw EhException();

}

return factory.create();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值