例如:
代碼
public class Order
{
private Guid _id;
private DateTime _creationDate;
private int _shippingMethod;
private int _status;
private List _orderItems;
public Guid Id
{
get { return _id; }
set { _id = value; }
}
public List 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 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ù)表是一一對應的關(guān)系,例如在開發(fā)博客或者論壇,Active Record方式就很合適。
相信很多的項目都是基于這個方式在開發(fā)和組織邏輯層,這個方式最大的弊端就是:數(shù)據(jù)庫表只要改動,那么業(yè)務邏輯層動,而且這種變動會一直波及到了UI那端。
Domain Model
通過用這種方式來組織業(yè)務層的時候,業(yè)務層就只是關(guān)注把現(xiàn)實中的概念轉(zhuǎn)換為相應的業(yè)務邏輯模型,不關(guān)注其他的方面。例如,在電子商務網(wǎng)站開發(fā)中,一些概念就被建模表示為一個個的業(yè)務模型(也就是業(yè)務類),Order, Shopping Cart, Customer等。而且和Active Record最大的區(qū)別就是:Domain Model中的業(yè)務類不是和表一一對應的,下圖就是一個很好的例子:
|