一、什么是多態(tài)
多態(tài):不同對象以自己的方式響應相同的消息的能力叫做多態(tài)。
由于每個類都屬于該類的名字空間,這使得多態(tài)稱為可能。類定義中的名字和類定義外的名字并不會沖突。類的實例變量和類方法有如下特點:
和C語言中結(jié)構(gòu)體中的數(shù)據(jù)成員一樣,類的實例變量也位于該類獨有的名字空間。
類方法也同樣位于該類獨有的名字空間。與C語言中的方法名不同,類的方法名并不是一個全局符號。一個類中的方法名不會和其他類中同樣的方法名沖突。兩個完全不同的類可以實現(xiàn)同一個方法。
方法名是對象接口的一部分。對象收到的消息的名字就是調(diào)用的方法的名字。因為不同的對象可以有同名的方法,所以對象必須能理解消息的含義。同樣的消息發(fā)給不同的對象,導致的操作并不相同。
多態(tài)的主要好處就是簡化了編程接口。它容許在類和類之間重用一些習慣性的命名,而不用為每一個新加的函數(shù)命名一個新名字。這樣,編程接口就是一些抽象的行為的集合,從而和實現(xiàn)接口的類的區(qū)分開來。
Objective-C支持方法名的多態(tài),但不支持參數(shù)和操作符的多態(tài)。
二、多肽的應用舉例
有一個tableView,它有多種cell,cell的UI差距較大,但是他們的model類型又都是一樣的。由于這幾種的cell都具有相同類型的model,那么肯定先創(chuàng)建一個基類cell,如:
@interface BaseCell : UITableViewCell
@property (nonatomic, strong) Model *model;
@end
然后各種cell繼承自這個基類cell
紅綠藍三種子類cell如下類似
@interface BaseCell : UITableViewCell
@property (nonatomic, strong) Model *model;
@end
子類cell重寫B(tài)aseCell的setModel方法
// 重寫父類的setModel:方法
- (void)setModel:(Model *)model {
? ? // 調(diào)用父類的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 {
? ? staticNSString *cellResueID = nil;
? ? cellResueID = self.cellReuseIdArray[indexPath.section];
? ? // 父類BaseCell *cell = [tableView dequeueReusableCellWithIdentifier:cellResueID];
? ? // 創(chuàng)建不同的子類if(!cell) {
? ? ? ? switch (indexPath.section) {
? ? ? ? ? ? case0:// 紅? ? ? ? ? ? {
? ? ? ? ? ? ? ? // 父類指針指向子類cell = [[RedCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellResueID];
? ? ? ? ? ? }
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? case1:// 綠? ? ? ? ? ? {
? ? ? ? ? ? ? ? // 父類指針指向子類cell = [[GreenCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellResueID];
? ? ? ? ? ? }
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? case2:// 藍? ? ? ? ? ? {
? ? ? ? ? ? ? ? // 父類指針指向子類cell = [[BlueCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellResueID];
? ? ? ? ? ? }
? ? ? ? ? ? ? ? break;
? ? ? ? }
? ? }
? ? // 這里會調(diào)用各個子類的setModel:方法cell.model = self.dataArray[indexPath.row];
? ? return cell;
}
一句話概括多態(tài):子類重寫父類的方法,父類指針指向子類。
多態(tài)的三個條件
繼承:各種cell繼承自BaseCell
重寫:子類cell重寫B(tài)aseCell的set方法
父類cel指針指向子類cell
以上就是多態(tài)在實際開發(fā)中的簡單應用,合理使用多態(tài)可以降低代碼的耦合度,可以讓代碼更易拓展。
鏈接:
https://www.cnblogs.com/guohai-stronger/p/10232467.html
http://www.itdecent.cn/p/26fab97c51ba