OOP引入封裝、繼承和多態性等概念來創建一種對象層次結構,用以模擬公共行爲的一個集合。當咱們須要爲分散的對象引入公共行爲的時候,OOP則顯得無能爲力。也就是說,OOP容許你定義從上到下的關係,但並不適合定義從左到右的關係。html
AOP技術則偏偏相反,它利用一種稱爲「橫切」的技術,剖解開封裝的對象內部,並將那些影響了多個類的公共行爲封裝到一個可重用模塊,並將其名爲「Aspect」,即方面。spring
AOP把軟件系統分爲兩個部分:核心關注點和橫切關注點。業務處理的主要流程是核心關注點,與之關係不大的部分是橫切關注點。橫切關注點的一個特色是,他們常常發生在覈心關注點的多處,而各處都基本類似。好比權限認證、日誌、事務處理。編程
實現AOP的技術,主要分爲兩大類:緩存
1. 一是採用動態代理技術,利用截取消息的方式,對該消息進行裝飾,以取代原有對象行爲的執行;性能優化
2. 二是採用靜態織入的方式,引入特定的語法建立「方面」,從而使得編譯器能夠在編譯期間織入有關「方面」的代碼。框架
實現AOP的技術特性:工具
一、 join point(鏈接點):是程序執行中的一個精確執行點,例如類中的一個方法。它是一個抽象的概念,在實現AOP時,並不須要去定義一個join point。post
二、 point cut(切入點):本質上是一個捕獲鏈接點的結構。在AOP中,能夠定義一個point cut,來捕獲相關方法的調用。性能
三、 advice(通知):是point cut的執行代碼,是執行「方面」的具體邏輯。優化
四、 aspect(方面):point cut和advice結合起來就是aspect,它相似於OOP中定義的一個類,但它表明的更可能是對象間橫向的關係。
五、 introduce(引入):爲對象引入附加的方法或屬性,從而達到修改對象結構的目的。有的AOP工具又將其稱爲mixin。
用途:
l Authentication 權限
l Caching 緩存
l Context passing 內容傳遞
l Error handling 錯誤處理
l Lazy loading 懶加載
l Debugging 調試
l logging, tracing, profiling and monitoring 記錄跟蹤 優化 校準
l Performance optimization 性能優化
l Persistence 持久化
l Resource pooling 資源池
l Synchronization 同步
l Transactions 事務
其它參考:
1. AOP是什麼?
2. 百度百科-面向切面編程
.NET原生的AOP技術實現:
l 使用Decorator Pattern實現,參考《Head First Design Patterns》第三章
l 使用.NET Remoting(RealProxy,ContextBoundObject),
a) 參考RealProxy 類,The simplest AOP scenario in C#
b) 使用Dynamic Proxy Pattern,參考Dynamic Decorator Pattern,Add Aspects to Object Using Dynamic Decorator,Dynamic Decorator and Castle DynamicProxy Comparison
c) .Net平臺AOP技術研究,在.Net中關於AOP的實現(補遺)
第三方的.NET AOP框架:
l 動態代理技術
n Encase
n LOOM.NET(同時提供動態和靜態兩種方式)
l 靜態織入:
n Eos-AOP
n RAIL - Runtime Assembly Instrumentation Library(靜態橫切)
Using Decorator Pattern:
Using .NET Remoting
Using Castle DynamicProxy
參考:
l Document of Castle DynamicProxy
l Castle's DynamicProxy for .NET
Using Spring.NET
參考:
各類方式優缺點比較:
方式 |
優勢 |
缺點 |
使用Decorator Pattern實現 |
l 須要實現大量的Decorator l Decorator不能複用(和用AOP以前一樣的問題) |
|
使用.NET Remoting |
l must extend MarshalByRef or ContextBoundObject (which carries another semantic) l mess with your object model hierarchy |
|
Castle DynamicProxy |
l Good Performance |
|
Spring.NET AOP |
l 強大的配置 |