Core Design Patterns(16) Chain of Responsibility 职责链模式
VS 2008
多个对象构成一个链式结构,客户端向链中的某个对象发出请求,被请求的对象可以处理客户代码的请求,也可以根据业务将请求向下传递,依此类推,直到请求最终被某对象处理,或抛出异常。这就是职责链模式的应用场景。
1. 模式UML图

2. 代码示例
例子仅为演示职责链模式。
软件从业人员,可能分SE, SSE, PL, PM等不同级别,有些工作可能按工作性质需要不同级别的人员才能处理,对于自己不能处理的工作,那么,他需要将请求传递给下家。

IWorker.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.ChainOfResponsibility.BLL {

public interface IWorker {

void DoWork(int level);
}
}
SE.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.ChainOfResponsibility.BLL {
public class SE : IWorker {

private IWorker next;

public SE(IWorker next) {
this.next = next;
}

IWorker Members
}
}
SSE.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.ChainOfResponsibility.BLL {
public class SSE : IWorker {

private IWorker next;

public SSE(IWorker next) {
this.next = next;
}

IWorker Members
}
}
PL.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.ChainOfResponsibility.BLL {
public class PL : IWorker {

private IWorker next;

public PL(IWorker next) {
this.next = next;
}

IWorker Members
}
}
PM.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.ChainOfResponsibility.BLL {
public class PM : IWorker {

private IWorker next;

public PM(IWorker next) {
this.next = next;
}

IWorker Members
}
}
Client
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DesignPattern.ChainOfResponsibility.BLL;

namespace DesignPattern.ChainOfResponsibility {
class Program {
static void Main(string[] args) {

IWorker worker = new SE(new SSE(new PL(new PM(null))));
worker.DoWork(3);
}
}
}
Output
多个对象构成一个链式结构,客户端向链中的某个对象发出请求,被请求的对象可以处理客户代码的请求,也可以根据业务将请求向下传递,依此类推,直到请求最终被某对象处理,或抛出异常。这就是职责链模式的应用场景。
1. 模式UML图

2. 代码示例
例子仅为演示职责链模式。
软件从业人员,可能分SE, SSE, PL, PM等不同级别,有些工作可能按工作性质需要不同级别的人员才能处理,对于自己不能处理的工作,那么,他需要将请求传递给下家。

IWorker.cs













SE.cs


















SSE.cs


















PL.cs


















PM.cs


















Client
















Output
