【发布时间】:2011-06-19 03:25:06
【问题描述】:
这是我用于模拟模型的类“层次结构”的一部分(我的代码使用 Python,但我认为我的问题与语言无关):
class World:
# highest-level class, which "knows" everything about the model
# most likely will have just one instance
# contains (e.g., in a dictionary) references to all the instances of class Agent
class Agent:
# each instance represents an agent
# an agent can, among other things, move around according to certain rules
# movement depends on the internal state of the agent,
# but also on the terrain and other information not stored in the Agent instance
问题:move 实例方法应该放在哪里?
我认为我应该将class Agent 的依赖限制在层次结构中低于自身的类(即,其实例包含在Agent 实例中的类)。但这意味着move 方法不能在class Agent 中,因为它创建了对描述地形等的类(至少是接口)的依赖——所以我不妨在Agent 中添加对(因此依赖于)World。从软件设计的角度来看,这可以吗?
另一种方法是将方法move 放在class World 中,它不会导致任何额外的依赖关系。但是,class World 将完成几乎所有的工作,在我看来,这将违背 OOP 的主要思想(我理解为不是将所有功能都集中在一个地方,而是将其包含在相关类)。
性能方面的考虑只是次要问题(而且我认为这两种方法的性能不会有所不同)。
编辑:我误用了上面的“类层次结构”一词。我指的不是继承层次结构,只是指一组实例相互包含的类。
【问题讨论】:
-
为了公平起见,我不认为我会这样做。在编写之前尝试编写一些“使用”您的域的代码,然后填写空白。从外部开始,向内工作通常会有所帮助。有不少关于域设计和建模的书籍可供参考。
-
您有什么参考资料您认为可能会有所帮助吗?我在亚马逊上只找到一本关于域设计的书:amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/…。
标签: python oop language-agnostic software-design