Objective-C

代理设计模式

2019-02-25  本文已影响1人  越天高

1.代理设计模式


2.代理设计模式示例

// 协议
#import <Foundation/Foundation.h>
@class Baby;

@protocol BabyProtocol <NSObject>
- (void)feedWithBaby:(Baby *)baby;
- (void)hypnosisWithBaby:(Baby *)baby;
@end
#import "BabyProtocol.h"
@interface Baby : NSObject
// 食量
@property (nonatomic, assign) int food;
// 睡意
@property (nonatomic, assign) int drowsiness;
// 饿
- (void)hungry;
// 睡意
- (void)sleepy;
@property (nonatomic, strong) id<BabyProtocol> nanny;
@end

@implementation Baby

- (void)hungry
{
    self.food -= 5;
    NSLog(@"婴儿饿了");
    // 通知保姆
    if ([self.nanny respondsToSelector:@selector(feedWithBaby:)]) {
        [self.nanny feedWithBaby:self];
    }
}

- (void)sleepy
{
    self.drowsiness += 5;
    NSLog(@"婴儿困了");
    // 通知保姆
    if ([self.nanny respondsToSelector:@selector(hypnosisWithBaby:)]) {
        [self.nanny hypnosisWithBaby:self];
    }
}
@end
// 保姆
@interface Nanny : NSObject <BabyProtocol>
@end

@implementation Nanny

- (void)feedWithBaby:(Baby *)baby
{
    baby.food += 10;
    NSLog(@"给婴儿喂奶, 现在的食量是%i", baby.food);
}

- (void)hypnosisWithBaby:(Baby *)baby
{
    baby.drowsiness += 10;
    NSLog(@"哄婴儿睡觉, 现在的睡意是%i", baby.drowsiness);
}
@end

3.代理设计模式练习

5.一般情况下一个类中的代理属于的名称叫做 delegate

6.当某一个类要成为另外一个类的代理的时候,
一般情况下在.h中用@protocol 协议名称;告诉当前类 这是一个协议.
在.m中用#import真正的导入一个协议的声明

@class Person;

@protocol PersonProtocol <NSObject>

- (void)personFindHourse:(Person *)person;

@end

@interface Person : NSObject

//@property (nonatomic, strong) id<StudentProtocol> delegete;
@property (nonatomic, strong) id<PersonProtocol> delegate;

- (void)findHourse;
@end

#import "Person.h"

@implementation Person

- (void)findHourse
{
    NSLog(@"学生想找房子");
    // 通知代理帮他找房子
    if ([self.delegate respondsToSelector:@selector(personFindHourse:)]) {
        [self.delegate personFindHourse:self];
    }
}

@end

代理的代码:

#import <Foundation/Foundation.h>
#import "Person.h"

//@protocol PersonProtocol;

@interface LinkHome : NSObject <PersonProtocol>

@end

#import "LinkHome.h"

@implementation LinkHome

- (void)personFindHourse:(Person *)person
{
    NSLog(@"%s", __func__);
}
@end

结果
学生想找房子
[LinkHome personFindHourse:]
上一篇下一篇

猜你喜欢

热点阅读