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, 还是苹果的好用。

下一篇工厂模式

你可能感兴趣的:(iOS开发之设计模式 - 代理模式)