首页 > DDD与MVC

DDD与MVC

DDD~传说中的领域驱动和现在一般使用的MVC的先进性体现在什么地方~怎么才能做到真正的DDD开发,而不是一味的使用DDD的结构而做着MVC的开发呢?


我觉得这是两个不同的东西。没有可比性。。用DDD就不能用MVC?


DDD和MVC都是设计的一些指导原则。对于设计原则来说,合适的才是最好的,新的不一定更先进,同时新的也不一定和旧的相冲突。

DDD强调先建立领域模型,用代码实现的时候,相应地分出了领域层(Domain),通过领域对象的方式组织代码,方便复用。业务逻辑复杂,使用DDD可以降低系统的复杂度。但是如果业务逻辑比较简单的话,其实也不一定要用DDD。最多使用DDD的语言是Java和C#,这正体现了DDD主要适用于复杂的大型企业应用(这类应用一般基于Java和C#)。当然,如果撇开DDD那一套具体的设计模式,单单从思想层面,即“注重领域建模,使用领域抽象”来定义DDD的话,别的语言也许会说它们早已用别的途径实现了DDD——比如Ruby会说internal DSL就是用来领域建模的语言,DSL就是Ruby的领域层。

通常归类到DDD中的DCI(D,数据,领域模型;C,上下文,用例;I,交互,对象扮演的角色),有人认为它是MVC的掘墓人。其实DCI和MVC都是Trygve Reenskaug提出的设计范式,我们来看看他是怎么解释两者的:

There are many variants of MVC. The following is its simplest form that reflects the essence of MVC:

  • Model. The Model consists of objects that represent domain information.
  • View. The View is a transformation between invisible Model data and a presentation that lets the human user grasp its meaning. The View also accepts input from the user and updates the Model accordingly. (In some versions, there is a further separation of concern by splitting the View into two objects; one for output and one for input.)
  • Controller. The Controller is responsible for setting up and coordinating one or more Views. (E.g., by making a selection in one View visible in all Views where this is appropriate).

DCI is appropriate whenever two or more objects interact to achieve some purpose. An obvious candidate is the update of the display in response to a changed Model. This is done by a Context and its algorithm transforms invisible Model data to pixels on the display. A Model object will clearly play one of the Roles. A View is another. The display algorithm is coded as Role methods. Variables in the Context object are used to hold data that belong to the algorithm as a whole. They are exposed to the Role Methods as (auxiliary) Roles.

-- Trygve在object-composition邮件列表的发言

Trygve在这里指出,MVC的M就是一层包含领域信息的对象。也就是说,MVC的M相当于领域层。Tryvge解释道,DCI是描述多个对象互通消息协作完成一个任务的一个模式。比如MVC中的Model发生了改变,View需要根据特定的显示算法作相应地调整,那这里的Model和View其实都是扮演了不同角色的对象,彼此直接有交互,显示算法就是角色的方法,它们都在一个上下文环境之中。

从中可以看出,DCI和MVC从不同角度描述对象,谈不上谁取代谁的问题。

这里还有一个例子,是在ASP.NET MVC下实践DDD的。

(顺带提一下,Trygve说的MVC是经典MVC,和通常意义上web领域的MVC不一样,接受用户输入后V可以更新M,而在web MVC中V要通知C,让C更新M。这是因为和经典MVC适用的GUI本地程序的场景不同,在传统的Web MVC中,用户的输入通常会转化成http请求,对http请求需要解析,用户的输入也需要验证,然后服务器端需要一系列操作,因此采取的做法是让V通知C,而不是直接更新M,否则V里面就会有太多复杂的逻辑了。)

【热门文章】
【热门文章】