COR:使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。
好处:当客户提交一个请求时,请求是沿链传递直至有一个ConcreteHandler对象负责处理它。这就使得接收者和发送者都没有对方的明确信息,且链中的对象自己也并不知道链的结构。结果是职责链可简化对象的相互连接,它们仅需保持一个指向其后继者的引用,而不需要保持它所有的候选接受者的引用。可以随时地增加或修改处理一个请求的结构。增强了给对象指派职责的灵活性。注意,一个请求极有可能到了链的末端都得不到处理,或者因为没有正确配置而得不到处理。
abstract class Manager
{
protected string name;
protected Manager superior;
public Manager(string name)
{
this.name = name;
}
public void SetSuperior(Manager superior)
{
this.superior = superior;
}
abstract public void RequestApplications(Request request);
}
class CommonManager:Manager
{
public CommonManager(string name)
: base(name)
{ }
public override void RequestApplications(Request request)
{
if (request.RequestType == "请假" && request.Number <= 2)
{
Console.WriteLine(string.Format("{0}:{1}数量{2}被批准", name, request.RequestContent, request.Number));
}
else
{
if (superior != null)
{
superior.RequestApplications(request);
}
}
}
}
class Majordomo:Manager
{
public Majordomo(string name)
: base(name)
{ }
public override void RequestApplications(Request request)
{
if (request.RequestType == "请假" && request.Number <= 5)
{
Console.WriteLine(string.Format("{0}:{1}数量{2}被批准", name, request.RequestContent, request.Number));
}
else
{
if (superior != null)
{
superior.RequestApplications(request);
}
}
}
}
class GeneralManager:Manager
{
public GeneralManager(string name)
: base(name)
{ }
public override void RequestApplications(Request request)
{
if (request.RequestType == "请假")
{
Console.WriteLine(string.Format("{0}:{1}数量{2}被批准", name, request.RequestContent, request.Number));
}
else if (request.RequestType == "加薪" && request.Number <= 500)
{
Console.WriteLine(string.Format("{0}:{1}数量{2}被批准", name, request.RequestContent, request.Number));
}
else if (request.RequestType == "加薪" && request.Number > 500)
{
Console.WriteLine(string.Format("{0}{1}数量{2},以后再说了", name, request.RequestContent, request.Number));
}
}
}
class Request
{
public string RequestType
{
get;
set;
}
public string RequestContent
{
get;
set;
}
public int Number
{
get;
set;
}
}
Manager cm = new CommonManager("钟鑫");
Manager m = new Majordomo("张大力");
Manager gm = new GeneralManager("李先锋");
cm.SetSuperior(m);
m.SetSuperior(gm);
Request r1 = new Request();
r1.RequestType = "请假";
r1.RequestContent = "小菜请假";
r1.Number = 2;
cm.RequestApplications(r1);
Request r2 = new Request();
r2.RequestType = "请假";
r2.RequestContent = "大菜请假";
r2.Number = 5;
cm.RequestApplications(r2);
Request r3 = new Request();
r3.RequestType = "加薪";
r3.RequestContent = "吴辉加薪";
r3.Number = 500;
cm.RequestApplications(r3);
Request r4 = new Request();
r4.RequestType = "加薪";
r4.RequestContent = "小菜加薪";
r4.Number = 1000;
cm.RequestApplications(r4);