思考:
在开发中,如果使用了模板技术+一般处理程序开发,应用中用户的请求可能在程序中都存在一个共性的操作。
例如,每当执行请求时要检查用户是否是登陆,请求时检查用户是否具有相应权限等等的共性的操作,我们不可能每个页面都写上对于操作,那样显然不符合面向对象的思想,存在大量冗余。
如何去解决呢?
解决思路:
这样而来,可以让共性的操作在父类里完成,而具体的方法实现在子类里完成
范例代码:
子类
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using Blog.Common;
 6 namespace Blog.UI.Article_category
 7 {
 8     /// <summary>
 9     /// Handler1 的摘要说明
10     /// </summary>
11     public class Article_category_Controller : BaseHandler
12     {
13 
14         //方法名都要约定:每个请求名都为action,action的值,都是一般处理程序的方法
15         public void list(HttpContext context)
16         {
17          string output=   RazorHelper.RazorParsre("/Article_category/template/Blog_Category.cshtml");
18          context.Response.Write(output);
19         }
20             
21 
22      
23     }
24 }
父类
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Reflection;
 5 using System.Web;
 6 using System.Web.SessionState;
 7 namespace Blog.UI
 8 {
 9 
10 
11     public class BaseHandler:IHttpHandler,IRequiresSessionState
12     {
13 
14         //一般处理程序会第一个执行    ProcessRequest()方法,它自己没有,会找父类要,让父类统一来执行请求
15         public void ProcessRequest(HttpContext context)
16         {
17 
18             /*
19              在处理请求操作之前,这里可以处理应用程序要遵循的共性操作
20              
21              */
22 
23 
24 
25             
26             //客户端每个请求约定俗成url带上一个参数叫action,action代表该请求执行什么操作
27             if (string.IsNullOrEmpty(context.Request["action"]))
28             {
29                 return;
30             }
31             string action = context.Request["action"];
32 
33             //调用父类的方法,会是子类handler,利用反射获得类型
34             Type ty = this.GetType();
35             //根据这个类型,找到和action同名对应的方法,也就是说用action找到当前请求要执行的方法
36             MethodInfo method = ty.GetMethod(action);
37             if (method!=null)
38             {
39                 method.Invoke(this, new object[] { context });  //context是参数
40                 return;
41             }
42 
43 
44         }
45 
46 
47 
48 
49         public bool IsReusable
50         {
51             get
52             {
53                 return false;
54             }
55         }
56 
57 
58 
59     }
60 
61 
62      
63 
64 }
原文:http://www.cnblogs.com/green-jcx/p/5930698.html