美文网首页
iOS开发之设计模式 - 代理模式

iOS开发之设计模式 - 代理模式

作者: JoeyM | 来源:发表于2019-03-28 15:53 被阅读0次

    由《大话设计模式 - 代理模式》的OC和部分Swift的语言转义

    代理模式

    继上一篇《装饰模式》

    • 代理模式
    代理模式

    小明追求小美,让小王去送各种礼物。

    OC

    // 代理接口
    @interface GiveGift : NSObject
    - (void)giveDolls;
    - (void)giveFlowers;
    - (void)giveChocolate;
    @end
    
    @implementation GiveGift
    - (void)giveDolls {}
    - (void)giveFlowers {}
    - (void)giveChocolate {}
    @end
    
    // 被追求者类
    @interface SchoolGirl : NSObject
    @property (nonatomic, copy) NSString *name;
    @end
    
    @implementation SchoolGirl
    @end
    
    
    // 追求者类
    @interface Pursuit : GiveGift
    - (instancetype)pursuit:(SchoolGirl *)mm;
    @end
    
    @implementation Pursuit
    {
        SchoolGirl *_mm;
    }
    
    - (instancetype)pursuit:(SchoolGirl *)mm {
        _mm = mm;
        return self;
    }
    
    - (void)giveDolls {
        NSLog(@"giveDolls");
    }
    
    - (void)giveFlowers {
        NSLog(@"giveFlowers");
    }
    
    - (void)giveChocolate {
        NSLog(@"giveChocolate");
    }
    @end
    
    // 代理类
    @interface Proxy : GiveGift
    - (instancetype)proxy:(SchoolGirl *)mm;
    @end
    
    @implementation Proxy
    {
        Pursuit *_gg;
    }
    
    - (instancetype)proxy:(SchoolGirl *)mm {
        _gg = [[Pursuit new] pursuit:mm];
        return self;
    }
    
    - (void)giveChocolate {
        [_gg giveChocolate];
    }
    
    - (void)giveFlowers {
        [_gg giveFlowers];
    }
    
    - (void)giveDolls {
        [_gg giveDolls];
    }
    @end
    
    
    @interface ViewController3 ()
    @end
    
    @implementation ViewController3
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        SchoolGirl *jj = [SchoolGirl new];
        jj.name = @"JJ";
        
        Proxy *delegate = [[Proxy new] proxy:jj];
        [delegate giveChocolate];
        [delegate giveFlowers];
        [delegate giveDolls];
    }
    
    @end
    
    

    啧啧啧, 这个设计模式真的鬼畜, 相比苹果内部的delegate, 还是苹果的好用。

    下一篇工厂模式

    相关文章

      网友评论

          本文标题:iOS开发之设计模式 - 代理模式

          本文链接:https://www.haomeiwen.com/subject/bpzqbqtx.html