使用ActiveRecord您可以定義這樣一個類:活動記錄與存儲庫 - 優點和缺點?
class Contact
{
private String _name;
public String Name
{
get { return _name; }
set
{
if (value == String.IsNullOrWhiteSpace())
throw new ArgumentException(...);
else
_name = value;
}
}
public Boolean Validate() { ... /* check Name is unique in DB */ }
public Boolean Save() { ... }
public static List<Contact> Load() { ... }
}
雖然這是很好的和簡單的,我發現我的課變得非常臃腫邏輯事情的一個大組合!
使用分層/域設計可以定義同一類,如:
class Contact
{
[Required(AllowEmptyStrings=false)]
public String Name { get; set; }
}
class ContactService : IService
{
public List<Contact> LoadContacts() { return (new ContactRepository()).GetAll(); }
public Contact LoadContact(int id) { return (new ContactRepository()).GetById(id); }
public Boolean SaveContact(Contact contact)
{
if (new ContactValidator().Validate(contact))
new ContactRepository().Save(contact);
}
}
class ContactRepository : IRepository
{
public List<Contact> GetAll() { ... }
public Contact GetById(int Id) { ... }
public Boolean Save(Contact contact) { ... }
}
class ContactValidator : IValidator
{
public Boolean Validate(Contact contact) { ... /* check Name is unique in DB */ }
}
class UnitOfWork : IUnitOfWork
{
IRepository _contacts = null;
public UnitOfWork(IRepository contacts) { _contacts = contacts; }
public Commit() { _contacts.Save(); }
}
是如何從活動記錄=>分層設計遷移?
-
在名稱設定器
- 實體級別驗證=>保持(通過DataAnnotation ableit)
- 商業邏輯/規則驗證(唯一名稱)=>從實體移動到一個新的單獨的ContactValidator
- 保存邏輯= >移動到一個單獨的存儲庫模式類(也用的UnitOfWork)
- 負載邏輯=>移動到單獨的存儲庫
- 與存儲庫交互是通過一個新的ContactService(其將執行使用ContactValidator,ContactRepository,的UnitOfWork的,等 - 反對lettin g調用者與ContactRepository一起鬆動!)。
我在尋找同行對這種分層設計的認可/建議 - 我通常不會在活動記錄類型之外進行設計!任何評論贊賞。
注意 - 這個例子是故意簡單的(UnitOfWork沒有被真正使用,Repository/Validator的新功能將以不同的方式處理)。