是否应根据基础类的本体/语义或其功能来组织包

时间:2014-01-28 11:36:57

标签: java packages

假设我正在编写一个模拟所有类型车辆的应用程序。我现在应该根据不同类型的车辆组织包裹,例如,

com.example.vehiclesimulation.car
com.example.vehiclesimulation.truck
com.example.vehiclesimulation.bus
com.example.vehiclesimulation.motorcycle

或者它们是否应该在基于功能的结构中组织,例如,

com.example.vehiclesimulation.transmission
com.example.vehiclesimulation.interior
com.example.vehiclesimulation.steering
com.example.vehiclesimulation.electronics

当我们深入到结构中时,包结构通常变得复杂。无论是形成子包还是兄弟,都无能为力。在上面的例子中,我们可以将本体包作为父母,然后将所有功能包作为他们的孩子,反之亦然。那么哪一个更合适,为什么呢?

编辑:可以注意到,当存在更深层次时,这种区别变得更加复杂,并且在每个层次上,必须在两个轴之间选择。例如,类XYZHeadlight应该在c.e.vehiclesimulation.car.XYZ.electronics或c.e.vehiclesimulation.electronics.car.XYZ或c.e.vehiclesimulation.car.electronics.XYZ?

下。

2 个答案:

答案 0 :(得分:1)

我认为这实际上取决于包装的类型。你的榜样并不是一个好的例子。我会建议基于功能的结构,但重写示例如下:

com.example.vehicles.car
com.example.vehicles.truck
com.example.vehicles.bus
com.example.vehicles.motorcycle

但以下“事物”不是车辆 - 它们是可用于车辆的部件

com.example.vehicleparts.transmission
com.example.vehicleparts.interior
com.example.vehicleparts.steering
com.example.vehicleparts.electronics

现在在您的car中,您可以使用com.example.vehicleparts.transmission

但有时您可能想要使用package个私有字段和方法,在这种情况下,您可以将它们全部放在一个包中来处理它。

答案 1 :(得分:0)

我会根据他们的功能构建它们。我得到这个的唯一原因是能够在不同的车辆类型之间“共享”组件,例如我想,在公共汽车上使用的卡车的传输可以更好地放置在第二(功能 - 本体)结构中。尽管如此,我觉得这只是一种品味问题。