軟件測試開發技術.NET設計模式:工廠方法模式(Factory Method)[5] .NET開發
關鍵字:設計模式 IHttpHandlerFactory工廠:
1public interface IHttpHandlerFactory
2{
3 // Methods
4 IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated);
5 void ReleaseHandler(IHttpHandler handler);
6}
7
IHttpHandlerFactory.GetHandler是一個工廠方法模式的典型例子,在這個應用中,各個角色的設置如下:
抽象工廠角色:IHttpHandlerFactory
具體工廠角色:PageHandlerFactory
抽象產品角色:IHttpHandler
具體產品角色:ASP.SamplePage_aspx
進一步去理解
理解上面所說的之后,我們就可以去自定義工廠類來對特定的資源類型進行處理。第一步我們需要創建兩個類去分別實現IHttpHandlerFactory 和IHttpHandler這兩個接口。
1public class HttpHandlerFactoryImpl:IHttpHandlerFactory {
2
3 IHttpHandler IHttpHandlerFactory.GetHandler(
4 HttpContext context, String requestType,
5 String url, String pathTranslated ) {
6
7 return new HttpHandlerImpl();
8
9 }//IHttpHandlerFactory.GetHandler
10
11 void IHttpHandlerFactory.ReleaseHandler(
12 IHttpHandler handler) { /**//*no-op*/ }
13
14}//HttpHandlerFactoryImpl
15
16public class HttpHandlerImpl:IHttpHandler {
17
18 void IHttpHandler.ProcessRequest(HttpContext context) {
19
20 context.Response.Write("sample handler invoked");
21
22 }//ProcessRequest
23
24 bool IHttpHandler.IsReusable { get { return false; } }
25
26}//HttpHandlerImpl
27
第二步需要在配置文件中建立資源請求類型和處理程序之間的映射。我們希望當請求的類型為*.sample時進入我們自定義的處理程序,如下:
原文轉自:http://www.anti-gravitydesign.com