.NET Observer模式

来源:互联网 发布:forge软件 编辑:程序博客网 时间:2024/06/03 08:50

应用场景:net 框架下的HttpModule (.net2.0 代码)

         先看一下 Observer 模式结构图:

 

    再看一下.net框架中的应用结构图

    关于HttpApplication.InitModules()函数的调用代码如下

 

1private void InitModules()
2{
3    //根据CONFIG文件中的配置来进行相关Module的创建并返回集合
4    this._moduleCollection = RuntimeConfig.GetAppConfig().HttpModules.CreateModules();  
5    this.InitModulesCommon();
6}

 

而这里的CreateModules所进行初始化的代码如下

 1internal HttpModuleCollection CreateModules()
 2{
 3    HttpModuleCollection modules = new HttpModuleCollection();
 4    foreach (HttpModuleAction action in this.Modules)   //
 5    {
 6        modules.AddModule(action.Entry.ModuleName, action.Entry.Create());
 7    }

 8    modules.AddModule("DefaultAuthentication"new DefaultAuthenticationModule());
 9    return modules;
10}

 

  
而.net1.0 下的代码相对应的是:

 1internal HttpModuleCollection CreateModules()
 2{
 3    HttpModuleCollection modules = new HttpModuleCollection();
 4    foreach (ModulesEntry entry in this._list)  //arraylist类型,因此此处要存在转型操作
 5    {
 6        modules.AddModule(entry.ModuleName, entry.Create());
 7    }

 8    modules.AddModule("DefaultAuthentication"new DefaultAuthenticationModule());
 9    return modules;
10}

 

    看来差别并不大, 因此不就多说什么了。

 

 
//内部属性 HttpModules,完成从<httpModules>配置节点读取信息关初始化相关集合的任务,
//注.net1.0 框架下的代码在此处不完全相同,1.0下用 HttpModulesConfiguration,来返回集合。

1internal HttpModulesSection HttpModules
2{
3    get
4    {
5        return (HttpModulesSection) this.GetSection("system.web/httpModules"typeof(HttpModulesSection), 
6 ResultsIndex.HttpModules);
7    }

8}

9


//开始运行module中的init函数

 1private void InitModulesCommon()
 2{
 3    int count = this._moduleCollection.Count;
 4    for (int i = 0; i < count; i++)
 5    {
 6        this._currentModuleCollectionKey = this._moduleCollection.GetKey(i);
 7        this._moduleCollection[i].Init(this);  //此处代码将相关的module中的init函数
 8    }

 9    
10    .
11}

 


    思考:另外本人觉得httphandler实现所采用的模式与httpmodule方式不同。大家可以看一下HttpApplication类中的
ApplicationStepManager.BuildSteps(WaitCallback stepCallback)方法(会在HttpApplication.InitInternal被调用)中
有这个一段:

    ....
    steps.Add(new HttpApplication.MapHandlerExecutionStep(app)); 
    ....

         而MapHandlerExecutionStep,而它会调用自身的Execute(),近而调用MapHttpHandler--->GetAppLevelHandlerMapping以从
webconfig结点中加载匹配条件的处理程序绑定。因此从这方面,buildstep更像是一组装起来的流水线。而httphandler只是提供
一个零件而已, 但这个流水线从我个人角度看倒有点象是个"异步执行"的Observer结构,这里就不再分析了:)

0 0
原创粉丝点击