单一责任原则与贫血/富域模型有何关系? [英] How Single Responsibility Principle relates to anemic/rich domain model?

查看:125
本文介绍了单一责任原则与贫血/富域模型有何关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,在对从另一个团队接手的内容进行一些代码审查时,对于将SRP及其与贫血或富域模型(由Martin Fowler定义)之间的关系存在疑问. 富域模型的概念是拥有一个智能对象,该对象不仅可以设置/获取其属性,还可以执行一些更复杂的业务逻辑.我想知道它如何适合SRP?

Currently in doing some code review of stuff taken over from another team and have one doubt about applying SRP and its relation to anemic or rich domain model (as defined by Martin Fowler). Rich domain model concept is to have intelligent object that can not only set/get their properties but also can perform some more complicated business logic. I wond how it fits into SRP?

说,我的模型类具有一些可以暴露这些道具并对其属性进行简单计算的属性.下一个要求是可以将此对象数据存储在不受我控制的某个存储对象中,例如:

Say I have my model class having some properties that can expose those props and provide some simple calculations on its properies. Next requirement is to have possibility to store this object data in some storage object that is not under my control, like this:

class MyObject {
    // get set
    // parse sth

}

在存储中存储方法

   storage.store(key, object);

如果MyObject具有这样的存储方法,是否不违反SRP

Doesn't it violate SRP if MyObject has store method like this

public void store(Storage storage) {
    storage.store('keyOne', fieldOne);
    storage.store('keyTwo', fieldTwo);
}

从该对象的视角来看,最好是能够存储其状态. 其他方法可能是在此处引入某种服务,并像这样进行操作:

From this object's pov it is a good think to be able to store its state. Other way could be to introduce sort of service here and do this like that:

public StorageService {
    private Storage;
    // constructor here
    ....
    public void store(MyObject myobj);
}

您能为我指出有关此问题的任何链接吗?我在这里找到了一个线程,但并不能完全回答我的问题.

Can you point me any links I can read about this problem? I've found one thread on SO here but it doesn't answer my question completely.

在DDD中如何解决?根据定义,DDD中的模型非常丰富,可以看作是职责过多.

How is it resolved in DDD? Models in DDD are by definition rich and can be seen as having too many responsibilities.

推荐答案

富域模型( RDM )表示控制模型行为的逻辑 属于模型,而不是像使用getters/setter那样对待模型一样对待模型.这不是不是,意味着包括持久性,安全性,如何在GUI中显示模型等所有内容都必须在模型内.

A rich domain model (RDM) means that the logic governing the model's behavior belongs within the model, as opposed to treating the model like data with getters/setters. This does not mean everything including persistence, security, how to display the model in the GUI, etc. needs to be within the model.

RDM和SRP携手并进,彼此之间没有冲突.

RDM and SRP go hand-in-hand, they do not conflict with each other.

违反SRP/RDM:

Car {
   // possibly violates SRP
   storeInDatabase();  
   // smells like anemic domain model
   getEngineState();   
}

遵循SRP/RDM:

// usings aspects to remove cross-cutting concerns from the model and follow SRP
@DatabaseSerializable 
Car {
   // rich domain model encapsulates engine state and exposes behavior
   drive();            
}

这篇关于单一责任原则与贫血/富域模型有何关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆