iOS AOP編程思想及實踐

什麼是 AOP

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

  • Cross-cutting concerns:多個業務邏輯共有的非核心的邏輯(好比記錄日誌)。
  • Advice:具體的須要插入的非核心邏輯代碼(寫日誌邏輯)。
  • Pointcut:核心業務邏輯中的 Advice 插入點。
  • Aspect:Advice 與 Pointcut 合起來被稱爲 Aspect。

應用

來看一個例子。spa

如今要記錄全部 view controller 展現的日誌。.net

能夠想到的方法有:日誌

  • 最原始的方法:在每一個 view controller 的 viewWillAppear: 方法裏面增長寫日誌的代碼。
  • 稍微改進的代碼:寫一個 base view controller 添加記錄日誌的方法,全部的 view controller 都繼承它。
  • 使用 method swizzling 將全部的 viewWillAppear: 方法替換成原有邏輯加上寫日誌的邏輯——也就是 AOP 的方式。

顯然,對比一下這三種方式,毫無疑問最後一種方式不須要修改已有代碼,而且後期維護、增長新邏輯更方便。code

iOS 有一個著名的開源庫:Aspects,它利用 method swizzling 封裝出 API 讓你能夠在一個類的方法執行以前、以後(Pointcut)執行附加的邏輯(Advice)。orm

利用 Aspect,想要作到在全部的 view controller 顯示時記錄日誌只須要這樣:繼承

1
2
3
[UIViewController aspect_hookSelector:@selector(viewWillAppear:) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> aspectInfo, BOOL animated) {
NSLog(@"View Controller %@ will appear animated: %tu", aspectInfo.instance, animated);
} error:NULL];

這樣的好處很明顯:

  • 下降了程序的耦合度:你不須要修改業務代碼就能夠增長功能。
  • 增長了代碼的複用性:在全部的 pointcut 增長功能,只須要實現一次。

固然,上面只是一種實現方式而已,重要的是 AOP 的思想。

參考

相關文章
相關標籤/搜索