【问题标题】:Best pattern for strong typing of class relations类关系强类型的最佳模式
【发布时间】:2015-02-28 11:05:27
【问题描述】:

我正在寻找一种方法来允许在编译时实例之间的关系。 在抽象的方式中,这意味着接口的多个子类型与同一类型的多个属性相关,但并非所有子类型都以逻辑方式兼容。我想在编译时检查一下。

场景如:

  • 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") 
}

使用泛型或映射可能是一种棘手的方式...

【问题讨论】:

  • 这不是静态类型系统的工作。
  • 也许是一种解决方法...如果我的 API 可以通过域边界本身的代码处理它可能会很好

标签: java generics design-patterns interface composition


【解决方案1】:

你想要的是类似于 java 8 pluggable type system 的东西。

使用它的示例和框架是here

使用它来创建@Animal 和@Country 注释似乎完全有可能,但不一定明智。然后设置一个相应的类型检查器来查询appropriate database 以查看它们是否已经灭绝。

【讨论】:

  • 嗯,这是一个非常有趣的方法。我会研究是否可以在 Lion 类中制作“@Countries(津巴布韦,肯尼亚)”或在津巴布韦类中制作“@Animals(Lion,Gorilla)”。
猜你喜欢
  • 2011-03-17
  • 2015-12-23
  • 2014-07-05
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多