想象一下这种伪语言的映射
class Mapping{
key0 --> new ObjectValue()
key1 --> new ObjectValue()
key3 --> new ObjectValue1(String name)
key4 --> new ObjectValue2(String name, int age)
...
}
在此映射中,值由不同的构造函数实例化。当我调用任何键时,我想传递一些参数。
约束:所有键都从同一类扩展。
所有ObjectValues都从一个公共类扩展。
我希望方法调用返回
StaticMapping.key0.get(); // return new ObjectValue()
StaticMapping.key1.get(name); // return new ObjectValue1(String name)
如何做到这一点?这是什么模式?
AFAIK数据结构Map,enum constructor无法实现此目的。
最佳答案
因为所有键都具有不同的接口,最重要的是,键的数量不同,因此您必须为每个键定义一个新的类型。
它们必须具有公共的超级类型,这一事实也禁止将java.util.function
中的接口用作静态类型。
class KeySuper {...}
class KeyType0 extends KeySuper {
public ObjectValue get() {
return new ObjectValue();
}
}
class KeyType1 extends KeySuper {
public ObjectValue1 get(String str) {
return new ObjectValue1(str);
}
}
// Simmilar for KeyType2
class StaticMapping {
// public static final Supplier<ObjectValue> key0 = ObjectValue::new;
// ^^^ does not have the common super type...
public static final KeyType0 key0 = new KeyType0();
public static final KeyType0 key1 = new KeyType0();
public static final KeyType1 key2 = new KeyType1();
public static final KeyType2 key3 = new KeyType2();
}
还有其他选项,例如,使用
Object[]
,然后在运行时检查参数的数量和类型,如果参数不正确,则引发异常,这样您就可以拥有:abstract ObjectValue get(Object...);
在超级类型上定义,实际上似乎没什么用。