• 浅尝DesignPattern_ChainOfResponsibility


    UML:

    通过让多个对象都有机会处理该请求,来避免耦合请求的发送者的接收器,链接接收对象并且通过链来传递请求直到一个对象处理它

    Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it. 

    Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it. 

    • Handler   ()
      • defines an interface for handling the requests
      • 定义一个处理请求的接口
      • (optional) implements the successor link
      • 实现successor链接
    • ConcreteHandler   ()
      • handles requests it is responsible for
      • 处理负责的请求
      • can access its successor
      • 能够访问successor 
      • if the ConcreteHandler can handle the request, it does so; otherwise it forwards the request to its successor
      • 如果ConcreteHandler能处理请求,它也可以.
    • Client   ()
      • initiates the request to a ConcreteHandler object on the chain  
      • 启动链上的请求

    Sample:

    abstract class Handler
    {
    protected Handler successor;
    public void SetSuccessor(Handler successor)
    {
    this.successor = successor;
    }
    public abstract void HandleRequest(int request);
    }
    class ConcreteHandler1:Handler
    {
    public override void HandleRequest(int request)
    {
    if (request >= 0 && request < 10)
    {
    Console.WriteLine(
    "{0} handled request {1}",
    this.GetType().Name, request);
    }
    else if (successor != null)
    {
    successor.HandleRequest(request);
    }
    }
    }
    class ConcreteHandler2:Handler
    {
    public override void HandleRequest(int request)
    {
    if (request >= 10 && request < 20)
    {
    Console.WriteLine(
    "{0} handled request {1}",
    this.GetType().Name, request);
    }
    else if (successor != null)
    {
    successor.HandleRequest(request);
    }
    }
    }
    class ConcreteHandler3:Handler
    {
    public override void HandleRequest(int request)
    {
    if (request >= 20 && request < 30)
    {
    Console.WriteLine(
    "{0} handled request {1}",
    this.GetType().Name, request);
    }
    else if (successor != null)
    {
    successor.HandleRequest(request);
    }
    }
    }
    #region ChainOR
    Handler h1
    = new ConcreteHandler1();
    Handler h2
    = new ConcreteHandler2();
    Handler h3
    = new ConcreteHandler3();
    h1.SetSuccessor(h2);
    h2.SetSuccessor(h3);

    int[] requests = { 2, 5, 14, 22, 18, 3, 27, 20 };
    foreach (int request in requests)
    {
    h1.HandleRequest(request);
    }
    #endregion
  • 相关阅读:
    java中的接口
    java中的多态
    java中的继承
    抽象和封装
    表单验证
    13、迭代器与生成器
    10、end关键字和Fibonacci series: 斐波纳契数列
    9、字典
    8、元组
    2、Python_Day_1_作业
  • 原文地址:https://www.cnblogs.com/TivonStone/p/1724741.html
Copyright © 2020-2023  润新知