而且最主要的特点就是:每个业务类包含了很多的业务验证,状态跟踪等。职责很单一,便于维护和理解。
示例代码如下:
代码
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业务类的一部分代码,但是从代码中可以看出,这个类中包含了很丰富的业务逻辑。例如,在Process方法中,处理了下面的流程:
1.调用CanProcess 方法来进行下面的验证:
a.Order的是否处于合适的可以被处理的状态
b.在Order中订购的物品是否有足够的库存
2.customer用户给这个order付款。至于怎么付款,这个逻辑就包含在了card类中。
3.然后,对产品的库存进行更新。
可以看出,采用Domain Model方式很适合来来组织复杂的业务逻辑,而且代码也很容易阅读和理解(如果在加上重构)。
3.总结
通过上面的一些分析和解释,不知道大家是否现在已经清楚:之前提出的问题如何解决。
一个建议就是:不要太形式化,根据项目的实际情况来。这句话可以使相当于废话,但是很多的情况确实是这样的,DDD不是万能的,Transaction Script和Active Record也有它们的优势,合适就好。
谢谢各位!
转载:http://www.cnblogs.com/yanyangtian/archive/2010/07/13/1776355.html
本文链接:http://www.blueidea.com/tech/program/2010/7844.asp
出处:博客园
责任编辑:bluehearts
上一页 asp.net架构设计解惑 [3] 下一页
◎进入论坛网络编程版块参加讨论
|