iOS | 多態(tài)的實際運用
一句話概括多態(tài):子類重寫父類的方法皆尔,父類指針指向子類丛肢。
或許你對多態(tài)的概念比較模糊垄潮,但是很可能你已經在不經意間運用了多態(tài)奇瘦。比如說:
有一個tableView,它有多種cell验靡,cell的UI差異較大倍宾,但是它們的model類型又都是一樣的。
由于這幾種cell都具有相同類型的model胜嗓,那么你肯定會先建一個基類cell高职,如:
@interface BaseCell : UITableViewCell@property (nonatomic, strong) Model *model;
@end
然后各種cell繼承自這個基類cell:
image
紅綠藍三種子類cell
@interface RedCell : BaseCell@end
子類cell重寫B(tài)aseCell的setModel:方法:
// 重寫父類的setModel:方法
- (void)setModel:(Model *)model { // 調用父類的setModel:方法 super.model = model;
// do something...}
在controller中:
// cell復用ID array- (NSArray *)cellReuseIdArray {
if (!_cellReuseIdArray) {
_cellReuseIdArray = @[RedCellReuseID, GreenCellReuseID, BlueCellReuseID];
}
return _cellReuseIdArray;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellResueID = nil;
cellResueID = self.cellReuseIdArray[indexPath.section];
// 父類
BaseCell *cell = [tableView dequeueReusableCellWithIdentifier:cellResueID];
// 創(chuàng)建不同的子類 if (!cell) {
switch (indexPath.section) {
case 0: // 紅 { // 父類指針指向子類
cell = [[RedCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellResueID]; } break;
case 1: // 綠 { // 父類指針指向子類
cell = [[GreenCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellResueID]; } break;
case 2: // 藍 { // 父類指針指向子類
cell = [[BlueCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellResueID]; } break;
}
}
// 這里會調用各個子類的setModel:方法
cell.model = self.dataArray[indexPath.row];
return cell;
}
不出意外,類似于上面的代碼我們都寫過兼蕊,其實這里就運用到了類的多態(tài)性初厚。
多態(tài)的三個條件:
繼承:各種cell繼承自BaseCell
重寫:子類cell重寫B(tài)aseCell的setModel:方法
指向:父類cell指針指向子類cell
以上件蚕,就是多態(tài)在實際開發(fā)中的體現(xiàn)孙技。
合理運用類的多態(tài)性可以降低代碼的耦合度讓代碼更易擴展。
原文:http://www.cocoachina.com/ios/20190107/26049.html