博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
二十六.职责链模式
阅读量:4319 次
发布时间:2019-06-06

本文共 1295 字,大约阅读时间需要 4 分钟。

职责连模式:

       ChainOfResponsibility:使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。

优点:

       请求是沿链传递至有一个ConcreteHandler对象处理它

       但要注意链尾是否能处理所有请求

Demo1

       //处理请求的接口

   abstract class Handler

    {

       protected Handler successor;

       public void SetSuccessor(Handler successor)//设置继任者

       {

           this.successor = successor;

       }

       //处理请求的抽象方法

       public abstract void HandlerRequest(int request);

    }

 

       // 有权处理0-10之间

   class ConcreteHandler1:Handler

    {

       public override voidHandlerRequest(int request)

       {

           if (request >= 0 && request < 10)

           {

                Console.WriteLine("{0}处理请求{1}",

                    this.GetType().Name,request);

           }

           else if (successor != null)

           {

               successor.HandlerRequest(request);//转移到下一位

           }

       }

    }

   // 有权处理10-20之间

   class ConcreteHandler2 : Handler

    {

       public override void HandlerRequest(int request)

       {

           if (request >= 10&& request < 20)

           {

                Console.WriteLine("{0}处理请求{1}",

                    this.GetType().Name,request);

           }

           else if (successor != null)

           {

                successor.HandlerRequest(request);//转移到下一位

           }

       }

}

。。。。。。

 

static void Main(string[]args)

       {

           Handler h1 = new ConcreteHandler1();

           Handler h2 = new ConcreteHandler2();

           Handler h3 = new ConcreteHandler3();

           h1.SetSuccessor(h2);

           h2.SetSuccessor(h3);

 

           int[] request = { 2,3,12,14,3,28};

           foreach (int i in request)

           {

                h1.HandlerRequest(i);

           }

 

           Console.ReadKey();

       }

 

 

转载于:https://www.cnblogs.com/yaoge/archive/2010/09/01/1815254.html

你可能感兴趣的文章
第二天作业
查看>>
访问属性和访问实例变量的区别
查看>>
Spring MVC 异常处理 - SimpleMappingExceptionResolver
查看>>
props 父组件给子组件传递参数
查看>>
【loj6038】「雅礼集训 2017 Day5」远行 树的直径+并查集+LCT
查看>>
十二种获取Spring的上下文环境ApplicationContext的方法
查看>>
UVA 11346 Probability 概率 (连续概率)
查看>>
linux uniq 命令
查看>>
Openssl rand命令
查看>>
HDU2825 Wireless Password 【AC自动机】【状压DP】
查看>>
BZOJ1015: [JSOI2008]星球大战starwar【并查集】【傻逼题】
查看>>
HUT-XXXX Strange display 容斥定理,线性规划
查看>>
mac修改用户名
查看>>
一道关于员工与部门查询的SQL笔试题
查看>>
Canvas基础
查看>>
[Hive - LanguageManual] Alter Table/Partition/Column
查看>>
可持久化数组
查看>>
去除IDEA报黄色/灰色的重复代码的下划波浪线
查看>>
Linux发送qq、网易邮件服务配置
查看>>
几道面试题
查看>>