1. 程式人生 > >23種設計模式

23種設計模式

{0} 項目 責任 lin git man next https com

一、責任鏈模式的介紹

責任鏈模式用簡單點的話來說,將責任一步一步傳下去,這就是責任,想到這個我們可以相當擊鼓傳花,這個是為了方便記憶,另外就是我們在項目中經常用到的審批流程等這一類的場景時我們就可以考慮是否可以使用責任鏈模式。下面的介紹將會按照這個審批的例子寫Demo;

二、責任鏈模式的Demo

//采購請求
public class PurchaseRequest
{
//金額
public double Amount { get; set; }
//產品名字
public string ProductName { get; set; }

public PurchaseRequest(double amount,string productName)
{
Amount = amount;
ProductName = productName;
}
}

//審批人。
public abstract class Approver
{

public Approver NextApprover { get; set; }

public string Name { get; set; }

public Approver(string name)
{
Name = name;
}

public abstract void ProcessRequest(PurchaseRequest purchaseRequset);

}

//管理者
public class Manager : Approver
{
public Manager(string name) : base(name)
{

}

public override void ProcessRequest(PurchaseRequest purchaseRequset)
{
if (purchaseRequset.Amount < 10000)
{
Console.WriteLine("{0}-{1} approved the request of purshing {2}", this, Name, purchaseRequset.ProductName);
}
else if(NextApprover!=null)
{
NextApprover.ProcessRequest(purchaseRequset);
}
}
}

//副總
public class VicePresident : Approver
{
public VicePresident(string name) : base(name)
{
}

public override void ProcessRequest(PurchaseRequest purchaseRequset)
{
if (purchaseRequset.Amount < 20000)
{
Console.WriteLine("{0}-{1} approved the request of purshing {2}", this, Name, purchaseRequset.ProductName);
}
else if (NextApprover != null)
{
NextApprover.ProcessRequest(purchaseRequset);
}
}
}

//總經理
public class President : Approver
{
public President(string name) : base(name)
{
}

public override void ProcessRequest(PurchaseRequest purchaseRequset)
{
if (purchaseRequset.Amount < 100000)
{
Console.WriteLine("{0}-{1} approved the request of purshing {2}", this, Name,
purchaseRequset.ProductName);
}
else
{
Console.WriteLine("我們需要組織會議");
}
}
}

三、Demo位置

GitHub:https://github.com/wangtongzhou520/Designpattern

  

23種設計模式