class 关系强类型的最佳模式
Best pattern for strong typing of class relations
我正在寻找一种在编译时允许实例之间建立关系的方法。
以抽象的方式,这意味着一个接口的多个子类型与同一类型的多个属性相关,但并非所有子类型都以逻辑方式兼容。我想在编译时检查它。
场景如:
- Animal 实例在构造函数(它所在的国家/地区)中接收一个国家/地区实例。
解决方案:
- 运行时检查 XML 例如和验证
<Animal>
<Type>Lion</Type>
<Countries>
<Country>Zimbabwe</Country>
<Country>Kenya</Country>
</Countries>
</Animal>
<Animal>
<Type>Gorilla</Type>
<Countries>
<Country>Zimbabwe</Country>
<Country>Botswana</Country>
</Countries>
</Animal>
但这只能在运行时失败
- 为每个属性组合创建一个GorillaCountry、BotswanaCountry和KenyaCountry Country子接口,但是如果有200个映射就有点难以维护了。
我寻找的是某种模式,它以一种很好的和可扩展的方式在编译时进行这种类型检查:
if (animal instanceOf Lion){
if (country instanceOf Botswana) throw new UnsupportedMapping("There are no lions in Botswana")
}
//for Kenya
else if (animal instanceOf Gorilla){
if (country instanceOf Kenya) throw new UnsupportedMapping("There are no gorillas in kenya")
}
可能是使用泛型或映射的棘手方法...
你想要的是 java 8 pluggable type system.
使用它的示例和框架是here。
使用它来创建@Animal 和@Country 注释似乎是完全可能的,尽管不一定明智。然后设置一个相应的类型检查器来查询 appropriate database 以查看它们是否已灭绝。
我正在寻找一种在编译时允许实例之间建立关系的方法。 以抽象的方式,这意味着一个接口的多个子类型与同一类型的多个属性相关,但并非所有子类型都以逻辑方式兼容。我想在编译时检查它。
场景如:
- Animal 实例在构造函数(它所在的国家/地区)中接收一个国家/地区实例。
解决方案:
- 运行时检查 XML 例如和验证
<Animal> <Type>Lion</Type> <Countries> <Country>Zimbabwe</Country> <Country>Kenya</Country> </Countries> </Animal> <Animal> <Type>Gorilla</Type> <Countries> <Country>Zimbabwe</Country> <Country>Botswana</Country> </Countries> </Animal>
但这只能在运行时失败
- 为每个属性组合创建一个GorillaCountry、BotswanaCountry和KenyaCountry Country子接口,但是如果有200个映射就有点难以维护了。
我寻找的是某种模式,它以一种很好的和可扩展的方式在编译时进行这种类型检查:
if (animal instanceOf Lion){
if (country instanceOf Botswana) throw new UnsupportedMapping("There are no lions in Botswana")
}
//for Kenya
else if (animal instanceOf Gorilla){
if (country instanceOf Kenya) throw new UnsupportedMapping("There are no gorillas in kenya")
}
可能是使用泛型或映射的棘手方法...
你想要的是 java 8 pluggable type system.
使用它的示例和框架是here。
使用它来创建@Animal 和@Country 注释似乎是完全可能的,尽管不一定明智。然后设置一个相应的类型检查器来查询 appropriate database 以查看它们是否已灭绝。