淺析架構(gòu)設計的新思路 DDD設計模式
前言:之前的文章,很多朋友發(fā)來了反饋,從反饋中也看出了一些問題,一個最明顯的問題就是:當我提到DAL的實現(xiàn)的時候,一些朋友就問:DAL中采用了Repository模式嗎? 初一看起來,可能認為這個問題沒有什么,其實仔細的想想就會發(fā)現(xiàn),確實在問題的背后隱藏的了另外的一個問題.
本篇的議題如下:
1. 問題的闡述
2. 設計方法
3. 總結(jié)
1. 問題的闡述
在項目中,我們一般都是分層,大家最熟悉的就是UI,BLL,DAL層,或者在加上一個Services服務層.一般的項目就這樣設計了.由于越來越多的公司,社區(qū)倡導領域驅(qū)動設計(DDD),于是,又有了項目的分層的方式,DDD設計中的一些概念也引入了: Presentation, Service, Domain, Repository. 而且一般來說,有下面的對應關系:
Presentation |
UI |
Domain |
BLL |
Repository |
DAL |
但是在開發(fā)的時候,一會兒在項目中建立一個Domain的類庫,一會兒又在項目建立DAL,***的情況就是:UI, Domain, DAL等等. 其實這倒是沒有什么,說到底只是一個名稱的問題,但是在只后面隱藏的問題就是:對DDD的不了解,很多的時候只是注重了”形”,而沒有領會到”神”.
在項目中不是建立了名稱為Presentation, Domain, Repository的類庫,這個項目就是DDD開發(fā)了,不是這樣的.本來在分層的時候采用UI,BLL,DAL,自己是很熟悉的,但是這樣一攪和, ***反而把概念搞復雜了.
而且,在項目中,是采用原來樸實的那種三層,還是采用DDD開發(fā),是要經(jīng)過思考的,不是那DDD的方法來套.也就是說,不要為了DDD而DDD.就像當初我們學習設計模式一樣,沒有必要在寫代碼的過程中為了設計模式而設計模式.
2. 設計方法
到底是采用DDD還是那種樸實的三層,主要取決與業(yè)務層的設計和系統(tǒng)的復雜度.
如果系統(tǒng)確實很復雜,業(yè)務邏輯相當?shù)膹碗s,那么建議采用DDD,因為DDD的引入就是用解決復雜性的.因為采用DDD的方法來設計業(yè)務邏輯層,那么業(yè)務邏輯層就只是關注業(yè)務邏輯的處理,至于怎么存儲和獲取數(shù)據(jù),絲毫不關心,所以基于這個原因,在DDD中就引入了Repository的概念,Repository就是來輔助業(yè)務邏輯層處理數(shù)據(jù)的.
雖然我一直在提”樸實的三層”,其實DDD和它之間沒有什么很明顯的劃分了,這里我之所以特意的把他們劃分出來,主要就是因為我們在項目開發(fā)中一般是三層(或者N層),這里提出主要是為便于后面講述一些問題.
下面就開始講述一些業(yè)務邏輯層設計方法,相信大家看完之后,很多的疑惑就迎刃而解了.
業(yè)務層的設計方法有三種:Transaction Script, Active Record和Domain Model.
看過Flower的<<企業(yè)架構(gòu)模式>>一書的朋友應該對上面的三個詞語很熟悉,在書中,這些概念講的確實很精煉,可能因為精煉,所以理解起來就不是很容易.
在本篇文章中,就涉及到了這些知識,只有把這些點講清楚了,之前的問題就能解決.
如果熟悉這些概念的朋友,也不妨看看,大家可以交流!
首先來看看Transaction Script(之所以沒有翻譯為中文,因為翻譯后的中文意思很容易讓人產(chǎn)生誤導)
其實Transaction Script就是過程化的設計方式,最直觀表現(xiàn)就是一個個的方法,每個方法做一個業(yè)務的流程。我們來看下面一個例子。例子的背景就是在電子商務網(wǎng)站中訂單的處理流程。
- public class OrderManager
- {
- public void PlaceOrder(OrderDTO order)
- {
- // Validate order based on business rules
- // Check for stock availablity on items ordered
- // Add the order to the database
- // Set the order id on the OrderDTO object
- }
- public bool CancelOrder(Guid orderId)
- {
- // Retrieve order from database
- // Determine if the order can be canceled
- // if order can be canceled, set as canceled
- // return true/false if order was canceled
- }
- public bool AddItemToOrder(Guid orderId, OrderItemDTO ItemToAdd)
- {
- // Retrieve order from database
- // Determine if the item can be added to the order
- // Add a new item row in the database
- // return true/false if item was added to the order
- }
- public bool ProcessOrder(Guid orderId)
- {
- // Check to ensure this order can be processed.
- // Validate order based on business rules
- // Update the stock levels of products ordered
- // return true/false if order was processed
- }
- }
在上面的代碼中,所有和訂單處理有關的邏輯都寫在OrderManager類中。類中的每一個方法就對應業(yè)務邏輯中的一個流程或者說對應一個use case,例如:CancelOrder就是取消訂單。
通過Transaction Script的方式來組織業(yè)務邏輯,一個很好的好處就是直觀,很容易理解代碼在做什么。如果有新的流程來了,再加一個方法就行了。
同時,這種組織方式的弊端就在于,當系統(tǒng)中的業(yè)務變得多而且復雜的時候,那么這樣的方法就開始變多,***的結(jié)果就是一個類中有成百上千個方法。而且這些方法中,除了一些基本的驗證可以提取為方法重用,其他的流程控制代碼在很多的地方要重寫,特別是當有兩個流程差不多的時候,代碼不可避免的重新寫。于是,這樣的類開始變得龐大而難以管理。
Active Record
這種組織方式已經(jīng)是我們最熟悉的了。
在很多的項目中,我們的業(yè)務實體類基本和數(shù)據(jù)庫中表是一一對應的,例如一個Order業(yè)務類就是代表了數(shù)據(jù)庫中的Order表。而且在平時項目中,”樸實的三層(N層)”,一般都是基于這種方式在組織邏輯。
這種方式的***的區(qū)別就是每個業(yè)務類自己負責自己的數(shù)據(jù)存取,也就是說在業(yè)務類中包含了業(yè)務邏輯的處理和數(shù)據(jù)的存取。
例如:
- public class Order
- {
- private Guid _id;
- private DateTime _creationDate;
- private int _shippingMethod;
- private int _status;
- private List<OrderItems> _orderItems;
- public Guid Id
- {
- get { return _id; }
- set { _id = value; }
- }
- public List<OrderItems> OrderItems
- {
- get { return _orderItems; }
- set { _orderItems = value; }
- }
- // Business Logic
- public void Place()
- {
- // Validate order based on business rules to ensure it is in
- // a good state to add to the database
- // Check for stock availablity on items ordered
- this.Add();
- }
- public void Cancel()
- {
- // Check to ensure this order can be canceled.
- this.Status = Status.Cancelled();
- this.Save();
- }
- public void ProcessOrder()
- {
- // Check to ensure this order can be processed.
- // Validate order based on business rules
- // Udpate the stock levels of products ordered
- }
- // Data Access Methods
- public void Save()
- {
- // Code to persist changes to the database
- }
- public void Add()
- {
- // Code to Add this object to the database
- }
- public void Delete()
- {
- // Code to remove this object from the database
- }
- public static List<Order> FindAll()
- {
- // Code to retrive all Orders from the database
- }
- public static Order FindBy(Guid id)
- {
- // Code to retrive a specific Order from the database
- }
- }
上面的代碼中,Order類包含了業(yè)務邏輯處理的代碼,如Cancel, Process。通過這些方法也調(diào)用了數(shù)據(jù)訪問代碼來保存數(shù)據(jù)。
如果在開發(fā)的項目中,業(yè)務類和數(shù)據(jù)表是一一對應的關系,例如在開發(fā)博客或者論壇,Active Record方式就很合適。
相信很多的項目都是基于這個方式在開發(fā)和組織邏輯層,這個方式***的弊端就是:數(shù)據(jù)庫表只要改動,那么業(yè)務邏輯層動,而且這種變動會一直波及到了UI那端。
Domain Model
通過用這種方式來組織業(yè)務層的時候,業(yè)務層就只是關注把現(xiàn)實中的概念轉(zhuǎn)換為相應的業(yè)務邏輯模型,不關注其他的方面。例如,在電子商務網(wǎng)站開發(fā)中,一些概念就被建模表示為一個個的業(yè)務模型(也就是業(yè)務類),Order, Shopping Cart, Customer等。而且和Active Record***的區(qū)別就是:Domain Model中的業(yè)務類不是和表一一對應的,下圖就是一個很好的例子:
而且最主要的特點就是:每個業(yè)務類包含了很多的業(yè)務驗證,狀態(tài)跟蹤等。職責很單一,便于維護和理解。
示例代碼如下:
- public class Order
- {
- private Guid _id;
- public Guid Id
- {
- get { return _id; }
- set { _id = value; }
- }
- public float ShippingCost()
- {
- return ShippingMethod.ShippingCostTo(this.DispatchAddress, this.ItemsTotalWeight());
- }
- public float Total()
- {
- return DiscountOffer.TotalPriceWithDiscountOfferAppliedTo(
- this.Items, ShippingCost());
- }
- public void Process()
- {
- if (this.CanProcess())
- {
- // Charge the card
- Customer.Card.Charge(this.Total());
- // Set the status of the order
- this.Status = Status.Shipped;
- // Adjust the stock levels
- foreach (OrderItem item in Items)
- {
- item.Product.DecreaseStockBy(item.QtyOrdered);
- }
- else
- {
- throw new InvalidOrderStateForOperationException(
- String.Format(
- "Order {0} cannot be processed in its current state {1}",
- this.Id, this.Status.ToString());
- }
- }
- public bool CanProcess()
- {
- if (!this.Status == Status.Shipped && !this.Status = Status.Cancelled)
- {
- return (this.HasEnoughStockFor(me.Items) &&
- GetBrokenRules.Count() == 0);
- }
- else
- {
- return false;
- }
- }
- public List<BrokenBusinessRule> GetBrokenRules()
- {
- List<BrokenBusinessRule> brokenRules = new List<BrokenBusinessRule>();
- if (Customer == null)
- brokenRules.Add(new BrokenBusinessRule()
- {
- Property = "Customer",
- Rule = "An Order must have a Customer"
- });
- else if (Customer.GetBrokenRules().Count > 0)
- {
- AddToBrokenRulesList(brokenRules, Customer.GetBrokenRules());
- }
- if (DispatchAddress == null)
- brokenRules.Add(new BrokenBusinessRule()
- {
- Property = "DispatchAddress",
- Rule = "An Order must have a Dispatch Address"
- });
- else if (DispatchAddress.GetBrokenRules().Count > 0)
- {
- AddToBrokenRulesList(brokenRules,
- DispatchAddress.GetBrokenRules());
- }
- // ......
- return brokenRules;
- }
- }
Order業(yè)務類的一部分代碼,但是從代碼中可以看出,這個類中包含了很豐富的業(yè)務邏輯。例如,在Process方法中,處理了下面的流程:
1. 調(diào)用CanProcess 方法來進行下面的驗證:
a. Order的是否處于合適的可以被處理的狀態(tài)
b. 在Order中訂購的物品是否有足夠的庫存
2. customer用戶給這個order付款。至于怎么付款,這個邏輯就包含在了card類中。
3. 然后,對產(chǎn)品的庫存進行更新。
可以看出,采用Domain Model方式很適合來來組織復雜的業(yè)務邏輯,而且代碼也很容易閱讀和理解(如果在加上重構(gòu))。
3. 總結(jié)
通過上面的一些分析和解釋,不知道大家是否現(xiàn)在已經(jīng)清楚:之前提出的問題如何解決。
一個建議就是:不要太形式化,根據(jù)項目的實際情況來。這句話可以使相當于廢話,但是很多的情況確實是這樣的,DDD不是***的,Transaction Script和Active Record也有它們的優(yōu)勢,合適就好。
原文標題:架構(gòu)設計解惑
鏈接:http://www.cnblogs.com/yanyangtian/archive/2010/07/13/1776355.html
【編輯推薦】
- UML用例建模的慨念和應用
- Eclipse UML插件及其安裝步驟簡明介紹
- 解析五大UML圖形的建立步驟
- 專家指導 如何使Eclipse和UML工具EA進行連接
- 把Eclipse UML插件集成至Eclipse如何實現(xiàn)