设计模式学习17 Chain Of Responsibility
2010-07-23 20:47
585 查看
应用场景:
Chain the receiving objects and pass the request along the chain until an object handles it.实现代码:
class Request { } abstract class BaseHandler { public BaseHandler(BaseHandler next) { this.next = next; } // 下一个可能处理这个request的对象 // 这里相当于链表 private BaseHandler next; public BaseHandler Next { get { return this.next; } set { this.next = value; } } public abstract bool CanHandleRequest(Request request); // 默认的情况把请求转到下一个对象去处理 public virtual void HandleRequest(Request reqest) { if(this.next != null) { this.next.HandleRequest(reqest); } } } public class AHandler : BaseHandler { public AHandler(BaseHandler next) : base(next) { } public override bool CanHandleRequest(Request request) { return true; } public override void HandleRequest(Request request) { if (this.CanHandleRequest(request)) { // ... } else { base.HandleRequest(request); } } } public class BHandler : BaseHandler { public BHandler(BaseHandler next) : base(next) { } public override void HandleRequest(Request reqest) { throw new NotImplementedException(); } } public class CHandler : BaseHandler { public CHandler(BaseHandler next) : base(next) { } public override void HandleRequest(Request reqest) { throw new NotImplementedException(); } } class Sender { public void Process() { // 请求的处理者来负责请求处理 Request request = new Request(); BaseHandler aHandler = new AHandler(null); BaseHandler bHandler = new BHandler(aHandler); BaseHandler cHandler = new CHandler(bHandler); cHandler.HandleRequest(request); // requst赋值等工作 // arraylist需要客户来维护 ArrayList list = new ArrayList(); list.Add(new AHandler()); list.Add(new BHandler()); list.Add(new CHandler()); foreach (BaseHandler handler in list) { if (handler.CanHandleRequest(request)) handler.HandleRequest(request); } } } class Program { static void Main(string[] args) { Sender sender = new Sender(); sender.Process(); } }
相关文章推荐
- 设计模式学习17 Chain Of Responsibility
- [学习笔记]设计模式之Chain of Responsibility
- 设计模式学习之责任链模式(Chain of Responsibility,行为型模式)(22)
- 设计模式(17)-Chain of Responsibility Pattern
- 设计模式(17)-Chain of Responsibility Pattern
- [设计模式学习笔记]CHAIN OF RESPONSIBILITY(职责链)
- 设计模式(17)-Chain of Responsibility Pattern
- 设计模式(17)-Chain of Responsibility Pattern
- 设计模式学习总结-责任链模式(Chain of Responsibility Method)
- 步步为营 .NET 设计模式学习笔记 十九、Chain of Responsibility(职责链模式)
- 步步为营 .NET 设计模式学习笔记 十九、Chain of Responsibility(职责链模式)
- 设计模式(17)-Chain of Responsibility Pattern
- 设计模式(17)-Chain of Responsibility Pattern
- 步步为营 .NET 设计模式学习笔记 十九、Chain of Responsibility(职责链模式)
- 设计模式(17)-Chain of Responsibility Pattern
- 设计模式学习—责任链模式(Chain of Responsibility Design Pattern)
- 设计模式(17)-Chain of Responsibility Pattern
- C#设计模式(17)-Chain of Responsibility
- 设计模式18——Chain of Responsibility设计模式
- 设计模式----Chain of Responsibility(职责链)模式