我想对本地库中的类型调用外部供应商的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
}
}
这里的“猫”和“狗”是特定于供应商的设置.稍后我可能会转到一家法国供应商,其中这两个分别是“聊天”和“ 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()));
}