94
技術社區[雲棲]
NET框架中的 Observer 模式
應用場景:net 框架下的HttpModule (.net2.0 代碼)
先看一下 Observer 模式結構圖:

再看一下.net框架中的應用結構圖

關於HttpApplication.InitModules()函數的調用代碼如下
private void InitModules()2
{3
//根據CONFIG文件中的配置來進行相關Module的創建並返回集合4
this._moduleCollection = RuntimeConfig.GetAppConfig().HttpModules.CreateModules(); 5
this.InitModulesCommon();6
}
而這裏的CreateModules所進行初始化的代碼如下
internal 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 下的代碼相對應的是:
internal 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,來返回集合。
internal HttpModulesSection HttpModules2
{3
get4
{5
return (HttpModulesSection) this.GetSection("system.web/httpModules", typeof(HttpModulesSection), 6
ResultsIndex.HttpModules);7
}8
}9
//開始運行module中的init函數
private 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結構,這裏就不再分析了:)
注:關於web.config中的相關ADD,REMOVE,Clear 等屬性初始化設置可以參見ConfigurationElement類中的this[Configurati
onProperty prop]屬性(get將會初始化或返回相應的HttpModuleActionCollection集合,並提供給HttpApplication.CreateModules()
使用),以及ConfigurationSectionCollection類相關的方法。
另外說明的是HttpModulesSection 的派生於ConfigurationSection,而ConfigurationSection派生於ConfigurationElement。
相關聯的類如ConfigurationProperty,ConfigurationPropertyCollection()基本上都是類似於數據結構的封裝,看一下代碼
大家就該清楚了。
總體上說,Observer結構應該是一種很好掌握的模式,也很好理解。這裏再把這種模式的意圖和適用性拷貝如下,以加深理解:
意圖: 定義對象間的一種一對多的依賴關係,當一個對象的狀態發生改變時, 所有依賴於它的對象都得到通知並被自動更新。
適用性:
1.當一個抽象模型有兩個方麵, 其中一個方麵依賴於另一方麵。將這二者封裝在獨立的對象中以使它們可以各自獨立
地改變和複用。
2.當對一個對象的改變需要同時改變其它對象, 而不知道具體有多少對象有待改變。
3.當一個對象必須通知其它對象,而它又不能假定其它對象是誰。換言之, 你不希望這些對象是緊密耦合的。
最後更新:2017-04-02 03:42:39