Wikipedia 上的 AOP 定義:git
In computing, aspect-oriented programming (AOP) is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns. It does so by adding additional behavior to existing code (an advice) without modifying the code itself, instead separately specifying which code is modified via a 「pointcut」 specification, such as 「log all function calls when the function’s name begins with ‘set’」. This allows behaviors that are not central to the business logic (such as logging) to be added to a program without cluttering the code core to the functionality. AOP forms a basis for aspect-oriented software development.github
AOP(Aspect Oriented Programming,國內多譯做「面向切面編程」),它是在不修改原有代碼的前提下給程序添加功能的一種技術。這樣能夠將一些重複而又與主要業務邏輯無關的代碼抽離出來,減小了耦合性,增長了代碼複用性。編程
一些相關術語:app
來看一個例子。spa
如今要記錄全部 view controller 展現的日誌。.net
能夠想到的方法有:日誌
viewWillAppear:
方法裏面增長寫日誌的代碼。viewWillAppear:
方法替換成原有邏輯加上寫日誌的邏輯——也就是 AOP 的方式。顯然,對比一下這三種方式,毫無疑問最後一種方式不須要修改已有代碼,而且後期維護、增長新邏輯更方便。code
iOS 有一個著名的開源庫:Aspects,它利用 method swizzling 封裝出 API 讓你能夠在一個類的方法執行以前、以後(Pointcut)執行附加的邏輯(Advice)。orm
利用 Aspect,想要作到在全部的 view controller 顯示時記錄日誌只須要這樣:繼承
1 |
[UIViewController aspect_hookSelector:@selector(viewWillAppear:) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> aspectInfo, BOOL animated) { |
這樣的好處很明顯:
固然,上面只是一種實現方式而已,重要的是 AOP 的思想。