首页 > 编程 > C# > 正文

C#职责链模式实例详解

2019-10-29 21:40:51
字体:
来源:转载
供稿:网友

这篇文章主要介绍了C#职责链模式,以实例形式完整分析了C#职责链模式的相关技巧与实现方法,具有一定参考借鉴价值,需要的朋友可以参考下

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

ConcreteHandler1.cs如下:

 

 
  1. using System; 
  2. using System.Collections.Generic; 
  3. using System.Linq; 
  4. using System.Text; 
  5. namespace ConsoleApplication1 
  6. public class ConcreteHandler1:Handler 
  7. public override void HandRequest(int request) 
  8. if(request>0&&request<10) 
  9. Console.WriteLine("{0} 处理请求 {1}",this.GetType().Name,request); 
  10. else if(successor!=null
  11. successor.HandRequest(request); 

ConcreteHandler2.cs如下:

 

 
  1. using System; 
  2. using System.Collections.Generic; 
  3. using System.Linq; 
  4. using System.Text; 
  5. namespace ConsoleApplication1 
  6. public class ConcreteHandler2:Handler 
  7. public override void HandRequest(int request) 
  8. if (request > 10 && request < 20) 
  9. Console.WriteLine("{0} 处理请求 {1}"this.GetType().Name, request); 
  10. else if (successor != null
  11. successor.HandRequest(request); 

ConcreteHandler3.cs如下:

 

 
  1. using System; 
  2. using System.Collections.Generic; 
  3. using System.Linq; 
  4. using System.Text; 
  5. namespace ConsoleApplication1 
  6. public class ConcreteHandler3:Handler 
  7. public override void HandRequest(int request) 
  8. if (request > 20 && request < 30) 
  9. Console.WriteLine("{0} 处理请求 {1}"this.GetType().Name, request); 
  10. else if (successor != null
  11. successor.HandRequest(request); 

Handler.cs如下:

 

 
  1. using System; 
  2. using System.Collections.Generic; 
  3. using System.Linq; 
  4. using System.Text; 
  5. namespace ConsoleApplication1 
  6. public abstract class Handler 
  7. protected Handler successor; 
  8. public void SetSuccessor(Handler successor)  
  9. this.successor = successor; 
  10. public abstract void HandRequest(int request); 

Program.cs如下:

 

 
  1. using System; 
  2. using System.Collections.Generic; 
  3. using System.Linq; 
  4. using System.Text; 
  5. namespace ConsoleApplication1 
  6. class Program 
  7. static void Main(string[] args) 
  8. Handler h1 = new ConcreteHandler1(); 
  9. Handler h2 = new ConcreteHandler2(); 
  10. Handler h3 = new ConcreteHandler3(); 
  11. h1.SetSuccessor(h2); 
  12. h2.SetSuccessor(h3); 
  13. int[] requests = {2,5,14,22,18,3,27,20}; 
  14. foreach(int request in requests) 
  15. h1.HandRequest(request); 
  16. Console.ReadKey(); 

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表