多态

iOS | 多态的实际运用

一句话概括多态:子类重写父类的方法,父类指针指向子类。

或许你对多态的概念比较模糊,但是很可能你已经在不经意间运用了多态。比如说:

有一个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重写BaseCell的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];    
    // 创建不同的子类    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;
}

不出意外,类似于上面的代码我们都写过,其实这里就运用到了类的多态性。

多态的三个条件:

  • 继承:各种cell继承自BaseCell

  • 重写:子类cell重写BaseCell的setModel:方法

  • 指向:父类cell指针指向子类cell

以上,就是多态在实际开发中的体现。

合理运用类的多态性可以降低代码的耦合度让代码更易扩展。
原文:http://www.cocoachina.com/ios/20190107/26049.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容