應用程式框架實戰十七:DDD分層架構之值物件(層超型別篇)
阿新 • • 發佈:2018-12-27
using System.Collections.Generic;
using System.Text;
using Util.Validations;
namespace Util.Domains {
/// <summary>
/// 領域層頂級基類
/// </summary>
public abstract class DomainBase {
#region 構造方法
/// <summary>
/// 初始化領域層頂級基類
/// </summary>
protected DomainBase() {
_rules = new List<IValidationRule>();
_handler = new ValidationHandler();
}
#endregion
#region 欄位
/// <summary>
/// 描述
/// </summary>
private StringBuilder _description;
/// <summary>
/// 驗證規則集合
/// </summary>
private readonly List<IValidationRule> _rules;
/// <summary>
/// 驗證處理器
/// </summary>
private IValidationHandler _handler;
#endregion
#region ToString(輸出領域物件的狀態)
/// <summary>
/// 輸出領域物件的狀態
/// </summary>
public override string ToString() {
_description = new StringBuilder();
AddDescriptions();
return _description.ToString().TrimEnd().TrimEnd( ',' );
}
/// <summary>
/// 新增描述
/// </summary>
protected virtual void AddDescriptions() {
}
/// <summary>
/// 新增描述
/// </summary>
protected void AddDescription( string description ) {
if ( string.IsNullOrWhiteSpace( description ) )
return;
_description.Append( description );
}
/// <summary>
/// 新增描述
/// </summary>
protected void AddDescription<T>( string name, T value ) {
if ( string.IsNullOrWhiteSpace( value.ToStr() ) )
return;
_description.AppendFormat( "{0}:{1},", name, value );
}
#endregion
#region SetValidationHandler(設定驗證處理器)
/// <summary>
/// 設定驗證處理器
/// </summary>
/// <param name="handler">驗證處理器</param>
public void SetValidationHandler( IValidationHandler handler ) {
if ( handler == null )
return;
_handler = handler;
}
#endregion
#region AddValidationRule(新增驗證規則)
/// <summary>
/// 新增驗證規則
/// </summary>
/// <param name="rule">驗證規則</param>
public void AddValidationRule( IValidationRule rule ) {
if ( rule == null )
return;
_rules.Add( rule );
}
#endregion
#region Validate(驗證)
/// <summary>
/// 驗證
/// </summary>
public virtual void Validate() {
var result = GetValidationResult();
HandleValidationResult( result );
}
/// <summary>
/// 獲取驗證結果
/// </summary>
private ValidationResultCollection GetValidationResult() {
var result = ValidationFactory.Create().Validate( this );
Validate( result );
foreach ( var rule in _rules )
result.Add( rule.Validate() );
return result;
}
/// <summary>
/// 驗證並新增到驗證結果集合
/// </summary>
/// <param name="results">驗證結果集合</param>
protected virtual void Validate( ValidationResultCollection results ) {
}
/// <summary>
/// 處理驗證結果
/// </summary>
private void HandleValidationResult( ValidationResultCollection results ) {
if ( results.IsValid )
return;
_handler.Handle( results );
}
#endregion
}
}