我想对我本地库中的类型调用外部供应商的 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/