案例:
假設(shè)現(xiàn)在有一個工具類刁岸,目的是把傳入頁面指定區(qū)域渲染成紅色
不好的設(shè)計
定義一個基類 BaseFlushedViewController: UIViewController
,返回一個 flushArea
, 供工具類進行染色虹曙。
class FlushHelper {
static func flush(_ viewController: BaseFlushedViewController) {
viewController.flushArea().backgroundColor = .red
}
}
class BaseFlushedViewController: UIViewController {
func flushArea() -> UIView {
return view
}
}
那么我們傳入的參數(shù)必須是他的子類,而且由于每個頁面可能需要刷新的視圖是不同的员淫,我們理論上應(yīng)該重寫他的 flushArea
方法
這樣做的問題有兩個:
- 新建的頁面類可能會忘記重寫該方法
- 如果需要傳入的頁面是一個
UINavigatiionController
或UITabbarController
呢?(有可能我現(xiàn)在要渲染導(dǎo)航欄或底部標(biāo)簽欄),那么我還要再在工具類中新增兩個接口適應(yīng)拴事。這顯然不是我們想要的
class FlushHelper {
static func flush(_ viewController: BaseFlushedViewController) {
viewController.flushArea().backgroundColor = .red
}
static func flush(_ viewController: BaseFlushedNavViewController) {
viewController.flushArea().backgroundColor = .red
}
static func flush(_ viewController: BaseFlushedTabViewController) {
viewController.flushArea().backgroundColor = .red
}
}
class BaseFlushedViewController: UIViewController {
func flushArea() -> UIView {
return view
}
}
class BaseFlushedNavViewController: UINavigationController {
func flushArea() -> UIView {
return view
}
}
class BaseFlushedTabViewController: UITabBarController {
func flushArea() -> UIView {
return tabBar
}
}
面相接口的設(shè)計
定義一個協(xié)議
protocol Flushable {
func flushArea() -> UIView
}
class FlushHelper {
static func flush(_ viewController: UIViewController & Flushable) {
viewController.flushArea().backgroundColor = .red
}
}
class SomeViewController: UIViewController, Flushable {
func flushArea() -> UIView {
return view
}
}
class SomeNavViewController: UINavigationController, Flushable {
func flushArea() -> UIView {
return navigationBar
}
}
class SomeFlushedTabViewController: UITabBarController, Flushable {
func flushArea() -> UIView {
return tabBar
}
}
將工具類的接口統(tǒng)一成 UIViewController & Flushable
這樣做的好處:
- 調(diào)用工具類接口時刃宵,十分明確的知道傳入的頁面要去實現(xiàn)
flushArea
方法,不存上文提到的在繼承之后忘記重寫的情況 - 適配所有的
UIViewController
及其子類牲证。不需要工具類再開放額外的接口
比較
看起來面向接口的方法和使用基類的方法相比,只是工具類中的接口統(tǒng)一成了一個。但實際上等太,面向接口的方法中,SomeNavViewController
和 SomeFlushedTabViewController
都是 UIViewController
的一種特例缩抡。而使用基類的實現(xiàn)方法中,三種 Base
類則是平級的基類瞻想,是為了覆蓋所有的頁面類型。
假設(shè)如果有一種新的導(dǎo)航頁面蘑险,那么面向基類的方法岳悟,就還要去新增一個新的基類覆蓋這個特例,面向接口的則只需要擴展出一個新的類型即可竿音,工具類接口不需要新增。
以上的思想春瞬,就是面向?qū)ο笤O(shè)計規(guī)則中 開閉原則的一種體現(xiàn)。