設計模式講的是「寫代碼之前該想什麼」,重構講的是「代碼跑通之後該改什麼」。這兩件事經常被混為一談,但它們出現的時機完全不同。本文結合 iOS 開發的實際場景,把常用模式與重構手法梳理一遍。
所有設計模式都是從這幾條原則演繹出來的:
a. 找出應用中可能變化之處,把它們獨立出來,不要和不需要變化的代碼混在一起;
b. 針對接口編程,而不是針對實現編程;
c. 多用組合,少用繼承;
d. 別調用我們,我們會調用你(好萊塢原則);
e. 一個類應該只有一個引起變化的原因。
五條裡最重要的是第一條——變化點隔離。判斷一段設計是否合格,只要問一句:需求變了,我要改幾個地方?答案越少越好。
模式的名字常常顯得抽象,配一個生活場景就好懂了:
· 觀察者模式(Subject/Observer):氣象台向各個布告板推送天氣;雜誌社向所有訂閱者寄送新刊。
· 裝飾者模式:星巴克點單時逐層疊加濃縮、牛奶、糖漿。
· 工廠模式:披薩店按口味生產;蓋章。
· 抽象工廠模式:不同地區的披薩店,各自生產符合當地口味的整套產品。
· 單例模式:巧克力工廠只有一個鍋爐。
· 命令模式:遙控器上的每一個按鈕,各自封裝一個可撤銷的操作。
· 適配器模式:插座轉接頭。
· 模板方法模式:泡茶與泡咖啡,步驟骨架相同、具體步驟不同。
· 迭代器與組合模式:餐廳併購煎餅屋後,需要統一遍歷兩套菜單。
· 狀態模式:糖果機與飲料機,內部狀態決定外部行為。
· 代理模式:代表他人完成某項職責。
· 複合模式:多個模式協同,解決反覆出現的複雜問題。
這裡不逐一展開,重點放在 iOS 開發中真正高頻使用的那幾個。
Cocoa 的整套框架建立在 MVC 之上,三個角色職責清晰:
1. 在模型對象中封裝數據與基本行為;
2. 用視圖對象向用戶展示信息;
3. 用控制器對象把模型與視圖連接起來。
實踐中最常見的偏差是「胖控制器」——模型退化成裸數據字典,視圖裡寫满業務判斷。一旦出現這種情況,MVC 就名存實亡了。
首先要區分「類」和「類型」:一個對象可以同時具備多個類型,不同類的對象也可以擁有相同的類型。凡是符合某個類型的對象(包括其子類),都能對針對該接口發出的請求作出響應。
Objective-C 裡實現接口的兩種手段是協議(@protocol)與抽象基類。
@protocol UITableViewDataSource
@required
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section;
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath;
@optional
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
- (nullable NSString *)tableView:(UITableView *)tableView
titleForHeaderInSection:(NSInteger)section;
@end
協議本身可以繼承其他協議,這也是 UIKit 的常見做法:
@protocol UITableViewDelegate // 協議可以遵守其他協議
@optional
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
- (CGFloat)tableView:(UITableView *)tableView
heightForRowAtIndexPath:(NSIndexPath *)indexPath;
- (CGFloat)tableView:(UITableView *)tableView
heightForHeaderInSection:(NSInteger)section;
@end
@required 與 @optional 的劃分本身就是一種設計表達:前者是契約,後者是可選的擴展點。設計自己的協議時,也要想清楚哪些方法是必須的。
類繼承是白箱復用——子類能看到父類的內部結構;對象組合是黑箱復用——你只通過接口使用對象,不關心它內部怎麼實現。正因耦合度更低,組合在應對變化時更從容。
舉一個真實場景:一個動態列表裡要展示多種類型的「發言」,包括純文字、圖文混排、音頻視頻、帶 @ 提及、帶地址、帶可見範圍等等。這時很難抽象出一個滿足所有需求的 Cell 基類;即使硬做出來,每種發言又有各自的交互,子類會迅速膨脹,耦合度急劇上升。
更合理的做法是讓每個 Cell 只負責自己的展示,把交互通過代理拋給外部:
// 通用容器 Cell
@interface YYHomeRecorderTableViewCell : UITableViewCell
@property (nonatomic, strong) UILabel *h_titleLable;
@property (nonatomic, strong) UILabel *h_contentLable;
@property (nonatomic, strong) UIButton *h_arrrowButton;
@property (nonatomic, strong) UIImageView *h_imgview;
- (void)hanleData:(NSString *)contentStr;
@end
// 具体生意 Cell:交互全部外抛
@protocol YYHomeRecorderSecondTableViewCellDelegate
- (void)secondTableIntoNextPage:(YYBaseViewController *)baseVC;
- (void)selectChangeScroll;
@end
@interface YYHomeRecorderSecondTableViewCell : UITableViewCell
@property (nonatomic, assign) id delegate;
@property (nonatomic, strong) NSArray *h_dataArray;
- (void)handleData:(NSArray *)opportunitySummary;
@end
// 客户分类信息 Cell
@protocol YYHomeRecorderThirdTableViewCellDelegate
- (void)thirdTableIntoNextPage:(YYBaseViewController *)baseVC;
@end
// 记录 Cell:右侧视图由侧滑状态决定显隐
@interface YYHomeRecorderForthTableViewCell : UITableViewCell
@property (nonatomic, strong) UIImageView *h_leftImg;
@property (nonatomic, strong) UILabel *h_contentLable;
@property (nonatomic, strong) UILabel *h_timeLable;
@property (nonatomic, strong) NSMutableArray *h_dataArray;
@property (nonatomic, strong) UIButton *h_rightImgButton; // 侧滑时出现
- (void)handelData:(YYDynamicResultListModel *)resultListModel;
@end
每個 Cell 通過自己的 delegate 協議把「點擊進入下一頁」「刪除選擇框」這類行為交給控制器處理,Cell 之間互不感知。新增一種發言類型時,只需新增一個 Cell 類,既有代碼一行都不用改——這就是開閉原則的實際模樣。
用戶信息、設備信息這類全局唯一的對象適合單例。dispatch_once 保證了線程安全與僅初始化一次:
+ (id)shareUserManager {
static SCRMUserManager *userManager;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
userManager = [[self alloc] init];
userManager.clientDevice = [[YYClientDeviceModel alloc] init];
userManager.accountInfo = [[AccountInfoModel alloc] init];
});
return userManager;
}
需要警惕的是單例被濫用成全局變量的替代品,那會讓依賴關係隱形化,測試也變得困難。
當對象之間存在一對多依賴、且需要鬆耦合地傳遞狀態變化時,通知是最直接的方案:
// 發送
[[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_LOGIN_LOGOUT
object:nil];
// 接收
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(loginOrLogout:)
name:NOTIFICATION_LOGIN_LOGOUT
object:nil];
// 必須在合適的時機移除,通常在 dealloc 中
[[NSNotificationCenter defaultCenter] removeObserver:self];
通知的缺點是調用關係離散、不利於排查,因此不適合承載複雜的數據流;這類場景更適合 delegate 或 Signal。
代理模式為其他對象提供一種代理,以控制對這個對象的訪問。A 類實現了 B 類中定義的協議,A 實際上就成了 B 的代理。
選擇 delegate 還是 Block,可以參考幾條經驗:
a. 如果對象有一個以上不同的事件源,用 delegate;
b. 如果對象是單例,不要用 delegate;
c. 如果請求需要攜帶附加信息,用 delegate 更清晰;
d. 如果用 Block 表達可能失敗的請求,只傳一個 Block,把成功與失敗分支寫在同一個閉包裡:
[fetcher makeRequest:^(id result) {
// 處理結果
} error:^(NSError *err) {
// 處理錯誤
}];
Block 的優勢是上下文連貫、不必跳轉到另一個方法;delegate 的優勢是接口明確、可擴展多個回調點。單一回調用 Block,多回調用 delegate,是實踐中比較穩的判斷標準。
快速迭代的項目裡,重複代碼不可避免。它不僅讓可讀性下降,更麻煩的是需求變更時——由於當初沒寫註釋,邏輯一層層堆在同一個方法裡,最後只有原作者能看懂,而原作者往往已經離開了。
不必要的傳參會讓方法簽名變得冗長,也讓調用方多寫好幾行毫無信息量的代碼。改寫前:
UIBarButtonItem *item = [self.navigationItem.rightBarButtonItems objectAtIndex:0];
UIButton *buttonItem = item.customView;
[self rightViewHidden:buttonItem];
- (void)rightViewHidden:(UIButton *)sender { ... }
改寫後:
[self rightViewHidden];
- (void)rightViewHidden {
UIBarButtonItem *item = [self.navigationItem.rightBarButtonItems objectAtIndex:0];
UIButton *buttonItem = item.customView;
...
}
判斷依據很簡單:只有當參數(尤其是類對象參數)在多次調用間確實會變化時,才值得把它提到方法簽名上。
當 A 控制器 push 到 B 控制器、而 B 的數據來自網絡時,如果在拿到數據後才創建視圖,網絡一旦失敗或超時,界面就是一片空白。把初始化提前:
- (void)viewDidLoad {
[super viewDidLoad];
[self initData];
[self initView];
}
視圖先以默認狀態呈現(骨架屏、占位文案、空態圖),網絡結果到達後再刷新內容。這既是穩健性問題,也是體驗問題。
滿屏的 view.tag == 402 沒有人能維護。用具語義的名字取代:
typedef NS_ENUM(NSUInteger, HeaderViewTag) {
HeaderViewTagBackImage = 400, // 背景圖
HeaderViewTagImportantImage, // 重要生意圖標
HeaderViewTagBussinessName, // 生意名稱
HeaderViewTagBussinessAmount, // 生意金額
HeaderViewTagBussinessAvatar, // 客戶頭像
HeaderViewTagBussinessCustomer, // 客戶名稱
HeaderViewTagDiscoverTime, // 發現日期
HeaderViewTagEstimateTime // 預計成交日期
};
某個選擇器頁面的 tableView 需要根據不同業務類型計算 frame。起初只有兩三種顯示類型,代碼是這樣的:
- (UITableView *)tableView {
if (!_tableView) {
_tableView = [[UITableView alloc] init];
if ([self needObjNumber]) {
if (_objType == YYObjTypeClue) {
_tableView.frame = CGRectMake(0, -(kTypeCellHeight*3)-64,
self.view.width, kTypeCellHeight*3);
} else {
if (_isMaster) {
_tableView.frame = CGRectMake(0, -(kTypeCellHeight*kTypeCount)-64,
self.view.width, kTypeCellHeight*kTypeCount);
} else {
_tableView.frame = CGRectMake(0, -(kTypeCellHeight*(kTypeCount-1))-64,
self.view.width, kTypeCellHeight*(kTypeCount-1));
}
}
} else if (_objType == YYObjTypeBriefing) {
...
} else if (_objType == YYObjTypeRelationCustomer) {
...
} else if (_objType == YYObjTypeBusinessDept || _objType == YYObjTypeLifeForm
|| _objType == YYObjTypeBusinessStage) {
...
}
// 還有三四個分支,每個分支都是一次 CGRectMake
_tableView.tableFooterView = [UIView new];
_tableView.delegate = self;
_tableView.dataSource = self;
}
return _tableView;
}
更糟的是 viewWillAppear: 裡還原封不動地抄了一遍同樣的判斷,只是包在動畫 block 裡。隨著業務類型增加到十幾種,這段代碼已經無法安全修改——改一處漏一處。
停下來分析它在做什麼:所有分支的本質只有一個變量——導航欄是否透明。導航欄透明時 tableView 要下移 64pt,不透明時貼頂。於是把「類型判斷」抽成一個語義清晰的謂詞方法:
// 導航欄是否透明
- (BOOL)navBarAlphaIsZero {
return (self.objType == YYObjTypeCustomer ||
self.objType == YYObjTypeBusiness ||
self.objType == YYObjTypeContact ||
self.objType == YYObjTypeBriefing ||
self.objType == YYObjTypeAttList ||
self.objType == YYObjTypeAttListTa);
}
frame 計算隨之簡化到極致——tableView 永遠與 self.view 等高,只是 y 偏移不同:
- (UITableView *)tableView {
if (!_tableView) {
_tableView = [[UITableView alloc] init];
CGRect frame = self.view.frame;
[_tableView setFrame:CGRectMake(0, -frame.size.height,
frame.size.width, frame.size.height)];
_tableView.tableFooterView = [UIView new];
_tableView.delegate = self;
_tableView.dataSource = self;
_tableView.backgroundColor = [UIColor clearColor];
}
return _tableView;
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
self.navigationController.navigationBar.translucent = NO;
[UIView animateWithDuration:0.6
delay:0
usingSpringWithDamping:0.7
initialSpringVelocity:10
options:UIViewAnimationOptionCurveEaseInOut
animations:^{
CGRect tableViewFrame = self.tableView.frame;
tableViewFrame.origin.y = [self navBarAlphaIsZero] ? 64 : 0;
[self.tableView setFrame:tableViewFrame];
} completion:^(BOOL finished) {
}];
}
這個例子值得反覆看:重構的關鍵不是把 if-else 搬來搬去,而是找出被埋在分支結構下面的那一個真正的變量。找到它,四十行判斷塌縮成一行布爾表達式;找不到,任何拆分都只是把混亂分散到更多地方。
設計模式是編碼前的功課,重構是編碼後的功夫,兩者服務於同一個目標:讓代碼在需求變化面前保持可修改性。
如果編程世界只有一條真理,那一定是「變化」。與其抵禦變化,不如主動規劃變化、迎接變化,並在每次變化後花一點時間讓代碼比原來更清晰一些。這種習慣日積月累,就是工程師素養的分水嶺。