应操作模型类成员的方法是在模型中还是在 Controller 中实现?这是否取决于这种操纵的“重度”?
我所说的“操纵”是指:
例如,
Board class
其中持有细胞矩阵成员。现在我想实现一个根据特定单元格位置返回所有周围单元格的方法。
模型或 View 是否负责实现上述内容?
如果这个问题属于另一个 Stack Exchange QA 站点,我将欢迎将我的帖子移至该站点的建议。
最佳答案
你所谓的“模型”其实是domain objects . MVC 中的实际模型只是一层,而不是具体的东西。
在您的特定示例中, Board
应该有一个返回这个列表的方法。我假设您实际上是在获取它,因为您需要与这些细胞进行进一步的交互。
这是services的地方在模型层内发挥作用。如果使用它们,它们是模型层的外部部分,包含应用程序逻辑 - 不同域对象之间的交互以及持久性(通常是 data mappers 或 units of work )与域对象之间的交互。
Let's say you are making a game, and you and player performs and AoE attack. Controller takes a hold of service, which is responsible for this functionality and sends a command: this player aimed AoE in this direction, perform it.
Service instantiates
Board
and asks for surrounding cells of the target location. Then it performs "damage" on every cell in the collection that it acquired. After the logic is done, it tell the Unit of Work instance to commit all the changes, that happened on theBoard
.
Controller 不关心服务做什么的细节。它不应该收到任何反馈。当执行到达 View 时,它从模型层请求最新的更改并修改 UI。作为额外的好处 - 服务让您可以阻止业务逻辑在表示层(主要由 View 和 Controller 组成)中泄漏。
域对象应该只包含处理其状态的方法。
关于model-view-controller - MVC - 除了 set/get 成员之外,哪些方法应该在 Model 类中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13550143/