思路分析:协议--代理者--主动者--主函数--基本上18分钟完成
1.协议:方法声明:喂婴儿吃饭,让婴儿睡觉
2.代理者:保姆-遵守协议-实现方法 - 主动者作为参数
3.婴儿类:>属性姓名,id<协议>-代理者 >方法声明:吃饭,睡觉 >方法实现:吃饭血量+20 睡觉血量+10---调用代理者
4.main函数创建对象,调用方法
#import <Foundation/Foundation.h>
// 1.协议:方法声明:喂婴儿吃饭,让婴儿睡觉
@class Baby;
@protocol EatFoodAndSleepProtocol <NSObject>
//喂婴儿吃饭
- (void)letBabyEatFood:(Baby *)baby;
//让婴儿睡觉
- (void)letBabySleep:(Baby *)baby;
@end
#import <Foundation/Foundation.h>
#import "EatFoodAndSleepProtocol.h"
#import "Baby.h"
//2.代理者:保姆-遵守协议-实现方法 - 主动者作为参数
@interface BaoMu : NSObject <EatFoodAndSleepProtocol>
//名字属性
@property(nonatomic,copy)NSString *name;
@end
#import "BaoMu.h"
//实现方法 - 主动者作为参数
@implementation BaoMu
//喂婴儿吃饭
- (void)letBabyEatFood:(Baby *)baby{
baby.blood +=20;
NSLog(@"%@吃饭了,血量变成了了%lf",baby.name,baby.blood);
}
//让婴儿睡觉
- (void)letBabySleep:(Baby *)baby{
baby.blood +=10;
NSLog(@"%@睡觉了,血量编程了%lf",baby.name,baby.blood);
}
@end
#import <Foundation/Foundation.h>
#import "EatFoodAndSleepProtocol.h"
@interface Baby : NSObject
//姓名属性
@property(nonatomic,copy)NSString *name;
//代理者属性
@property(nonatomic,strong)id<EatFoodAndSleepProtocol> delegate;
//血量属性
@property(nonatomic,assign)double blood;
//吃饭
- (void)eatFood;
//睡觉
-(void)sleep;
@end
#import "Baby.h"
@implementation Baby
//吃饭
- (void)eatFood{
NSLog(@"哇哇哇.....");
[self.delegate letBabyEatFood:self];
}
//睡觉
-(void)sleep{
NSLog(@"吃饱了");
[self.delegate letBabySleep:self];
}
@end
#import <Foundation/Foundation.h>
#import "BaoMu.h"
#import "BaoMu.h"
int main(int argc, const char * argv[]) {
//婴儿对象和属性
Baby *baby = [Baby new];
baby.name = @"妞妞";
baby.blood = 400;
//保姆对象
BaoMu *baoMu = [BaoMu new];
baoMu.name = @"保姆";
//代理者保姆
baby.delegate = baoMu;
//调用婴儿方法
[baby eatFood];
[baby sleep];
return 0;
}
|
|