23种设计模式
Posted 于继海
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了23种设计模式相关的知识,希望对你有一定的参考价值。
一、责任链模式的介绍
责任链模式用简单点的话来说,将责任一步一步传下去,这就是责任,想到这个我们可以相当击鼓传花,这个是为了方便记忆,另外就是我们在项目中经常用到的审批流程等这一类的场景时我们就可以考虑是否可以使用责任链模式。下面的介绍将会按照这个审批的例子写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种设计模式的主要内容,如果未能解决你的问题,请参考以下文章