加入了一些自己的想法,利用单例模式的思维对检查类进行静态化,节省了内存空间;利用中介者模式的思想,将链条的先后顺序放在“中介者”里定义,方便修改;
///
/// 检查平台,控制链执行的顺序
///
public class GoodsSale
{
private HandlerManager _handler = new HandlerManager();
private static SaleSecurityCheck _secuCheck = new SaleSecurityCheck();
private static SaleDataCheck _dataCheck = new SaleDataCheck();
private static SaleManager _manager = new SaleManager();
public bool Sale(string user, string customer, SaleModel model)
{
//1.检查权限
_handler.Successor = _secuCheck;
if (!_handler.sale(user, customer, model))
{
return false;
}
//2.检查数据
_handler.Successor = _dataCheck;
if (!_handler.sale(user, customer, model))
{
return false;
}
//3.确认收货
_handler.Successor = _manager;
if (!_handler.sale(user, customer, model))
{
return false;
}
return true;
}
}
///
/// 商品模型(实例用)
///
public class SaleModel
{
private string _goods;
private int _saleNum = 0;
public string Goods
{
get { return _goods; }
}
public int SaleNum
{
get { return _saleNum; }
}
public SaleModel(string goods, int num)
{
_goods = goods;
_saleNum = num;
}
public override string ToString()
{
string res = "none";
if (!string.IsNullOrEmpty(_goods))
{
res = "GoodsName: " + _goods + " Num: " + _saleNum;
}
return res;
}
}
///
/// 配置职责链的调用者
///
public class HandlerManager
{
private static SaleHandler _successor = null;
public SaleHandler Successor
{
get { return _successor; }
set { _successor = value; }
}
public bool sale(string user, string customer, SaleModel model)
{
return _successor.sale(user, customer, model);
}
}
///
/// 定义接口
///
public interface SaleHandler
{
bool sale(string user, string customer, SaleModel model);
}
///
/// 安全检查
///
public class SaleSecurityCheck : SaleHandler
{
public bool sale(string user, string customer, SaleModel model)
{
if (user.Equals("ycj"))
{
Console.WriteLine("pass security check");
return true;
}
return false;
}
}
///
/// 数据校验
///
public class SaleDataCheck : SaleHandler
{
public bool sale(string user, string customer, SaleModel model)
{
#region check
if (string.IsNullOrEmpty(user))
{
Console.WriteLine("none user");
return false;
}
if (string.IsNullOrEmpty(customer))
{
Console.WriteLine("none customer");
return false;
}
if (model == null)
{
Console.WriteLine("wrong model");
return false;
}
if (string.IsNullOrEmpty(model.Goods))
{
Console.WriteLine("none goods");
return false;
}
if (model.SaleNum <= 0)
{
Console.WriteLine("wrong salenum");
return false;
}
#endregion
Console.WriteLine("pass data check");
return true;
}
}
///
/// 执行收货
///
public class SaleManager : SaleHandler
{
public bool sale(string user, string customer, SaleModel model)
{
Console.WriteLine("user: {0}, customer: {1}", user, customer);
Console.WriteLine(model.ToString());
return true;
}
}
static void Main(string[] args)
{
SaleModel model = new SaleModel("test", 10);
GoodsSale sale = new GoodsSale();
if (sale.Sale("ycj", "lhq", model))
{
Console.WriteLine("ok");
}
else
{
Console.WriteLine("no");
}
Console.ReadKey();
}