java - 执行从类型层次结构到值集的一对一映射的高效设计模式

标签 java design-patterns polymorphism

我想对我本地库中的类型调用外部供应商的 api 方法。供应商的方法采用字符串形式的设置,可以采用多个值,例如 "Cat""Dog"。我正在执行从我的类型到供应商设置字符串的映射:

public class Program {
    interface LocalType {}
    static class LocalCat implements LocalType {}
    static class LocalDog implements LocalType {}

    // Calls some API to get the animal's sound
    interface AnimalSounds {
        void playSound(LocalType t);
    }

    // Vendor-specific implementation
    static class VendorSounds implements AnimalSounds{
        private static VendorAPI api = new VendorAPI();
        @Override public void playSound(LocalType t) {
            // Map local type to vendor setting
            if (t instanceof LocalCat)
                api.vendorMethod("Cat");
            else if (t instanceof LocalDog)
                api.vendorMethod("Dog");

        }
    }

    // API defined externally by vendor (reproduced here for illustration)
    static class VendorAPI {
        static void vendorMethod(String type) {
            // Do something
        }
    }

    public static void main(String[] args) {
        AnimalSounds s = new VendorSounds(); // Choose vendor
        s.playSound(new LocalCat()); // For example
    }
}

这里的"Cat""Dog" 是供应商特定的设置;稍后我可能会更改为法国供应商,其中这两个分别是 “Chat”“Chien”。因此,为了避免将特定于供应商的信息添加到 LocalType 层次结构中,这样每次我更换供应商时都必须更改,我将此映射隐藏在一种适配器 AnimalSounds 中(我添加了 VendorSounds 作为一个供应商的示例)。

但是 instanceof 的级联对我来说是糟糕的设计,是否有更优雅的方式来完成我忽略的这个?

最佳答案

如果你想将映射完全保留在本地类型之外,你可以构建一个 Map<Class,String> ,并使用它代替 instanceof 链基于条件:

static final Map<Class,String> vendorMethodMap = new HashMap<>;
static {
    // The data for this map could come from a configuration file of sorts
    vendorMethodMap.put(LocalCat.class, "Cat");
    vendorMethodMap.put(LocalDog.class, "Dog");
}

现在您的 playSound方法看起来像这样:

@Override public void playSound(LocalType t) {
    api.vendorMethod(vendorMethodMap.get(t.getClass()));
}

关于java - 执行从类型层次结构到值集的一对一映射的高效设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36266841/

相关文章:

php - 根据条件参数返回不同的对象

design-patterns - 如何在 Scala 中编写聚合模式?

scala - 为什么一些 Scala 方法使用多态参数而不是使用 Any/Nothing?

java - 如何识别我的项目中包含的不必要的 jar?

java - netty 中的 ctx.write() 和 ctx.channel().write() 有什么区别?

java - Hibernate 和 Spring 事务管理器 : Transaction Not Successfully Started

c++ - 重写的函数没有反射(reflect)在基类中,这是正常行为吗?

java - 初始化打包在 jar 文件中的 Spring bean

design-patterns - 关注点分离与松耦合

c++ - 如何让一个接口(interface)返回不同的数据类型?