在Java中创建一个不依赖于if-else的工厂方法 [英] Creating a factory method in Java that doesn't rely on if-else

查看:187
本文介绍了在Java中创建一个不依赖于if-else的工厂方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我有一个基于给定String充当工厂的方法。
例如:

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.
}

我想要做的是在类列表增长时避免整个if-else问题。
我想我需要有两个方法,一个将字符串注册到类,另一个根据操作的字符串返回类。

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.

用Java做这件事的好方法是什么?

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.

您可以创建工厂对象和从字符串到这些的映射。但这在当前的Java中确实有点冗长。

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<String,AnimalFactory> factoryMap =
    Collections.unmodifiableMap(new HashMap<String,AnimalFactory>() {{
        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();
}

在最初编写此答案时,用于JDK7的功能可能会使代码如下所示。事实证明,lambdas出现在Java SE 8中,据我所知,没有地图文字的计划。

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<String,AnimalFactory> 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();
}

这篇关于在Java中创建一个不依赖于if-else的工厂方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆