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

由《大话设计模式 - 代理模式》的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, 还是苹果的好用。

下一篇工厂模式

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容