欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#职责链模式实例详解

程序员文章站 2023-11-20 21:36:22
本文实例讲述了c#职责链模式。分享给大家供大家参考。具体如下: concretehandler1.cs如下: using system; us...

本文实例讲述了c#职责链模式。分享给大家供大家参考。具体如下:

concretehandler1.cs如下:

using system;
using system.collections.generic;
using system.linq;
using system.text;
namespace consoleapplication1
{
  public class concretehandler1:handler
  {
    public override void handrequest(int request)
    {
      if(request>0&&request<10)
      {
        console.writeline("{0} 处理请求 {1}",this.gettype().name,request);
      }
      else if(successor!=null)
      {
        successor.handrequest(request);
      }
    }
  }
}

concretehandler2.cs如下:

using system;
using system.collections.generic;
using system.linq;
using system.text;
namespace consoleapplication1
{
  public class concretehandler2:handler
  {
    public override void handrequest(int request)
    {
      if (request > 10 && request < 20)
      {
        console.writeline("{0} 处理请求 {1}", this.gettype().name, request);
      }
      else if (successor != null)
      {
        successor.handrequest(request);
      }
    }
  }
}

concretehandler3.cs如下:

using system;
using system.collections.generic;
using system.linq;
using system.text;
namespace consoleapplication1
{
  public class concretehandler3:handler
  {
    public override void handrequest(int request)
    {
      if (request > 20 && request < 30)
      {
        console.writeline("{0} 处理请求 {1}", this.gettype().name, request);
      }
      else if (successor != null)
      {
        successor.handrequest(request);
      }
    }
  }
}

handler.cs如下:

using system;
using system.collections.generic;
using system.linq;
using system.text;
namespace consoleapplication1
{
  public abstract class handler
  {
    protected handler successor;
    public void setsuccessor(handler successor) 
    {
      this.successor = successor;
    }
    public abstract void handrequest(int request);
  }
}

program.cs如下:

using system;
using system.collections.generic;
using system.linq;
using system.text;
namespace consoleapplication1
{
  class program
  {
    static void main(string[] args)
    {
      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.handrequest(request);
      }
      console.readkey();
    }
  }
}

希望本文所述对大家的c#程序设计有所帮助。