zoukankan      html  css  js  c++  java
  • 多态

    **多态 **

    • 一个对外接口(程序员编写的程序),多个内在实现(不同的机器代码)
    • 在OC程序中,体现为父类的指针可以指向子类的对象,从而调用子类中重写的父类方法

    使用形式
    ** a.**函数参数多态
    b.数组多态
    c.返回值多态

    多态:
    一个对外接口,多个内在实现(继承)

    多态实现:
    继承实现:本质:父类指针指向子类对象
    协议实现:本质:协议指针指向子类对象
    (注 :不可以调用其派生方法)

    多态使用形式:
    数组:(1)
    参数:(2)
    返回值:(3)

    继承多态形式:
    //数组多态

    void test3()
    {
        TRAnimal *a[3];
        a[0] = [[TRAnimal alloc] initWithName:@"无名氏" andAge:0];
        a[1] = [[TRDog alloc] initWithName:@"小黑子" andAge:3];
        a[2] = [[TRCat alloc] initWithName:@"老咪" andAge:1];
        for (int i = 0; i < 3; i++)
        {
            [a[i] eat];
        }
    }
    

    //参数多态

    void show(TRAnimal *a)
    {
        [a eat];
    }
    void test2()
    {
        TRDog *dog = [[TRDog alloc] initWithName:@"小黑子" andAge:3];
        show(dog);
        TRCat *cat = [[TRCat alloc] initWithName:@"老咪" andAge:1];
        show(cat);
    }
    

    //返回值多态

    typedef enum
    {
        ANIMAL, 
        DOG, 
        CAT,
    }Type;
    
    TRAnimal* get(Type type)
    {
        switch (type) {
            case ANIMAL:
                return [[TRAnimal alloc] initWithName:@"无名氏" andAge:0];
            case DOG:
                return [[TRDog alloc] initWithName:@"小黑子" andAge:3];
            case CAT:
                return [[TRCat alloc] initWithName:@"老咪" andAge:1];
        }
    }
    
    void test4()
    {
        [get(DOG) eat];
        [get(CAT) eat];
    }
    

    协议多态形式:
    //数组协议多态

    void test5()
    {
        id<TRProtocol2> b[2]; //b[i]只能调用协议中的方法,不能调用类中自定义的方法
        b[0] = [[TRClassA alloc] init];
        b[1] = [[TRClassB alloc] init];
        for (int i = 0; i < 2; i++)
        {
            [b[i] method1];
        }
    }
    

    //参数协议多态

    void fun(id<TRProtocol2> a)
    {
        [a method1];
    }
    void test6()
    {
        TRClassA *objA = [[TRClassA alloc] init];
        fun(objA);
        TRClassB *objB = [[TRClassB alloc] init];
        fun(objB);
    }
    

    //返回值协议多态

    typedef enum
    {
        CLASSA, CLASSB, CLASSC,
    }Type;
    id<TRProtocol2> get(Type type)
    {
        switch (type) {
            case CLASSA:
                return [[TRClassA alloc] init];
            case CLASSB:
                return [[TRClassB alloc] init];
            case CLASSC:
                return [[TRClassC alloc] init];
        }
    }
    void test7()
    {
        [get(CLASSA) method0];
        [get(CLASSB) method0];
    }
    

    Block多态:

    成功的三大原则: 1、坚持 2、不要脸 3、坚持不要脸
  • 相关阅读:
    交换函数swap的三种实现方法
    oracle如何修改某一列的数据类型
    安装 kibana 以及添加中文分词器
    linux 安装Elasticsearch
    docker添加tomcat容器成功无法访问首页
    docker run-it centos提示FATAL
    启动、重新启动容器后,进入交互模式
    获取阿里云docker加速器地址
    CentOS6 修改默认字符集为GBK
    linux中如何查看redis的版本
  • 原文地址:https://www.cnblogs.com/xulinmei/p/7413527.html
Copyright © 2011-2022 走看看