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

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

猜你喜欢

转载自www.cnblogs.com/guohai-stronger/p/10232467.html