iOS | 多態(tài)的實(shí)際運(yùn)用
一句話(huà)概括多態(tài):子類(lèi)重寫(xiě)父類(lèi)的方法,父類(lèi)指針指向子類(lèi)。
或許你對(duì)多態(tài)的概念比較模糊,但是很可能你已經(jīng)在不經(jīng)意間運(yùn)用了多態(tài)。比如說(shuō):
有一個(gè)tableView,它有多種cell,cell的UI差異較大,但是它們的model類(lèi)型又都是一樣的。
由于這幾種cell都具有相同類(lèi)型的model,那么你肯定會(huì)先建一個(gè)基類(lèi)cell,如:
@interface BaseCell : UITableViewCell@property (nonatomic, strong) Model *model;
@end
然后各種cell繼承自這個(gè)基類(lèi)cell:

image
紅綠藍(lán)三種子類(lèi)cell
@interface RedCell : BaseCell@end
子類(lèi)cell重寫(xiě)B(tài)aseCell的setModel:方法:
// 重寫(xiě)父類(lèi)的setModel:方法
- (void)setModel:(Model *)model { // 調(diào)用父類(lèi)的setModel:方法 super.model = model;
// do something...}
在controller中:
// cell復(fù)用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];
// 父類(lèi)
BaseCell *cell = [tableView dequeueReusableCellWithIdentifier:cellResueID];
// 創(chuàng)建不同的子類(lèi) if (!cell) {
switch (indexPath.section) {
case 0: // 紅 { // 父類(lèi)指針指向子類(lèi)
cell = [[RedCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellResueID]; } break;
case 1: // 綠 { // 父類(lèi)指針指向子類(lèi)
cell = [[GreenCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellResueID]; } break;
case 2: // 藍(lán) { // 父類(lèi)指針指向子類(lèi)
cell = [[BlueCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellResueID]; } break;
}
}
// 這里會(huì)調(diào)用各個(gè)子類(lèi)的setModel:方法
cell.model = self.dataArray[indexPath.row];
return cell;
}
不出意外,類(lèi)似于上面的代碼我們都寫(xiě)過(guò),其實(shí)這里就運(yùn)用到了類(lèi)的多態(tài)性。
多態(tài)的三個(gè)條件:
繼承:各種cell繼承自BaseCell
重寫(xiě):子類(lèi)cell重寫(xiě)B(tài)aseCell的setModel:方法
指向:父類(lèi)cell指針指向子類(lèi)cell
以上,就是多態(tài)在實(shí)際開(kāi)發(fā)中的體現(xiàn)。
合理運(yùn)用類(lèi)的多態(tài)性可以降低代碼的耦合度讓代碼更易擴(kuò)展。
原文:http://www.cocoachina.com/ios/20190107/26049.html