下面是使用指责链模式的一个具体的实例,可以方便的理解指责链模式。
其实指责链简单的来说,就是把一个指责的流程定义出来,像一条链路一样,每一个结点有自己的处理范围,若不能处理,则传到自己的引用的下一个结点。
下面的实例也是这样的一个简单的流程。每一笔预算需要不同的人审核,不同的人有不同的审核范围,若款项在自己的处理范围之内,就可以直接处理掉,若不在自己的范围内,就传入到自己的上级进行处理。在写实例的时候,就需要用户把处理的过程给定义出来。既是把那条处理的链路定义出来。
下面是示例的源代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Chain_of_Responsibility_Use
{
class PurchaseReuest
{
private int number;
private double amount;
private string purpose;
public PurchaseReuest(int number, double amount, string purpose)
{
this.amount = amount;
this.number = number;
this.purpose = purpose;
}
public int Number
{
get { return number; }
set { number = value; }
}
public double Amount
{
get { return amount; }
set { amount = value; }
}
public string Purpose
{
get { return purpose; }
set { purpose = value; }
}
}
abstract class Approver
{
protected string name;
protected Approver successor;
public Approver(string name)
{
this.name = name;
}
public void setSuccessor(Approver successor)
{
this.successor = successor;
}
abstract public void ProcessRequest(PurchaseReuest request);
}
//ConcreteHandler
class Director : Approver
{
public Director(string name)
: base(name) { }
public override void ProcessRequest(PurchaseReuest request)
{
//throw new NotImplementedException();
if (request.Amount < 10000.0)
Console.WriteLine("{0} {1} approved request# {2} ", this, name, request.Number);
else
if (successor != null)
successor.ProcessRequest(request);
}
}
//ConcreteHandler
class VicePresident : Approver
{
public VicePresident(string name) : base(name) { }
public override void ProcessRequest(PurchaseReuest request)
{
//throw new NotImplementedException();
if (request.Amount < 25000.0)
Console.WriteLine("{0} {1} approved request# {2} ", this, name, request.Number);
else
if (successor != null)
successor.ProcessRequest(request);
}
}
//ConcreteHandler
class President : Approver
{
public President(string name) : base(name) { }
public override void ProcessRequest(PurchaseReuest request)
{
//throw new NotImplementedException();
if (request.Amount < 100000.0)
Console.WriteLine("{0} {1} approved request# {2} ", this, name, request.Number);
else
Console.WriteLine("Request# {0} request " + "an executie meeting ! ", request.Number);
}
}
class Program
{
static void Main(string[] args)
{
Director Larry = new Director("Larry");
VicePresident Sam = new VicePresident("Sam");
President Tammy = new President("Tammy");
Larry.setSuccessor(Sam);
Sam.setSuccessor(Tammy);
PurchaseReuest rs = new PurchaseReuest(2034, 350.00, "Supplies");
Larry.ProcessRequest(rs);
PurchaseReuest rx = new PurchaseReuest(2035, 12590.10, "Project X");
Larry.ProcessRequest(rx);
PurchaseReuest ry = new PurchaseReuest(2036, 122100.00, "Project Y");
Larry.ProcessRequest(ry);
Console.ReadKey();
}
}
}
下面是示例的类图:
下面是示例的关系图:
示例的运行截图如下: