zoukankan      html  css  js  c++  java
  • iOS多态使用小结

    多态是面试程序设计(OOP)一个重要特征,但在iOS中,可能比较少的人会留意这个特征,实际上在开发中我们可能已经不经意的使用了多态。比如说:

    有一个tableView,它有多种cell,cell的UI差距较大,但是他们的model类型又都是一样的。由于这几种的cell都具有相同类型的model,那么肯定先创建一个基类cell,如:

    @interface BaseCell : UITableViewCell
    
    @property (nonatomic, strong) Model *model;
    
    @end

    然后各种cell继承自这个基类cell

     

    红绿蓝三种子类cell如下类似

    @interface BaseCell : UITableViewCell
    
    @property (nonatomic, strong) Model *model;
    
    @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;
    }
    复制代码

    这个在我本身的代码里面也会有,其实这里面也用了类的多态性。

     

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

    多态的三个条件

    1. 继承:各种cell继承自BaseCell
    2. 重写:子类cell重写BaseCell的set方法
    3. 父类cel指针指向子类cell

    以上就是多态在实际开发中的简单应用,合理使用多态可以降低代码的耦合度,可以让代码更易拓展。

  • 相关阅读:
    项目管理【53】 | 项目风险管理-规划风险应对
    Learning a Continuous Representation of 3D Molecular Structures with Deep Generative Models
    转:DenseNet
    转:期刊投稿中的简写(ADM,AE,EIC等)与流程状态解读
    论文中如何写算法伪代码
    氨基酸,多肽,蛋白质等
    pytorch查看全连接层的权重和梯度
    AI制药文章
    long-tail datasets
    转:Focal Loss理解
  • 原文地址:https://www.cnblogs.com/bigant9527/p/14681327.html
Copyright © 2011-2022 走看看