一 、 责任链模式的实际应用案例
下面的责任链模式代码演示了不同职务的人根据所设定的权限对一个购买请求作出决策或将其交给更高的决策者。
[C#] 纯文本查看 复制代码
using System;
// "Handler"
abstract class Approver
{
// Fields
protected string name;
protected Approver successor;
// Constructors
protected Approver(string name)
{
this.name = name;
}
// Methods
public void SetSuccessor(Approver successor)
{
this.successor = successor;
}
public abstract void ProcessRequest(PurchaseRequest request);
}
// "ConcreteHandler"
class Director : Approver
{
// Constructors
public Director(string name) : base(name) { }
// Methods
public override void ProcessRequest(PurchaseRequest request)
{
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
{
// Constructors
public VicePresident(string name) : base(name) { }
// Methods
public override void ProcessRequest(PurchaseRequest request)
{
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
{
// Constructors
public President(string name) : base(name) { }
// Methods
public override void ProcessRequest(PurchaseRequest request)
{
if (request.Amount < 100000.0)
Console.WriteLine("{0} {1} approved request# {2}",
this, name, request.Number);
else
Console.WriteLine("Request# {0} requires " +
"an executive meeting!", request.Number);
}
}
// Request details
class PurchaseRequest
{
// Member Fields
// Constructors
public PurchaseRequest(int number,
double amount, string purpose)
{
Number = number;
Amount = amount;
Purpose = purpose;
}
// Properties
public double Amount { get; set; }
public string Purpose { get; set; }
public int Number { get; set; }
}
/// <summary>
/// ChainApp Application
/// </summary>
public class ChainApp
{
public static void Main(string[] args)
{
// Setup Chain of Responsibility
Director Larry = new Director("Larry");
VicePresident Sam = new VicePresident("Sam");
President Tammy = new President("Tammy");
Larry.SetSuccessor(Sam);
Sam.SetSuccessor(Tammy);
// Generate and process different requests
PurchaseRequest rs = new PurchaseRequest(2034, 350.00, "Supplies");
Larry.ProcessRequest(rs);
PurchaseRequest rx = new PurchaseRequest(2035, 32590.10, "Project X");
Larry.ProcessRequest(rx);
PurchaseRequest ry = new PurchaseRequest(2036, 122100.00, "Project Y");
Larry.ProcessRequest(ry);
}
}
二 、 责任链模式的实现
责任链模式并不创建责任链。责任链的创建必须由系统的其它部分创建出来。
责任链模式降低了请求的发送端和接收端之间的耦合,使多个对象都有机会处理这个请求。一个链可以是一条线,
一个树,也可以是一个环。如下图所示,责任链是一个树结构的一部分。
|