main.m
#import <Foundation/Foundation.h>
#import "Girl.h"
#import "Boy.h"
int main(int argc, const char * argv[]) {
Girl *zongru = [Girl girlWithName:@"zongru" gender:@"f"];
Boy *lol = [Boy boyWithName:@"luoluo" gender:@"m"];
// 调用女孩类的_delegated的setter方法,将lol设置为女孩的代理
[zongru setDelegated:lol];
// 女孩饿了。
[zongru hungry];
[zongru poor];
return 0;
}
Boy.h
#import <Foundation/Foundation.h>
#import "Girl.h"
// 我们在父类后使用尖括号+协议名的方式表示:该类遵守某协议
@interface Boy : NSObject <YueFa>
{
NSString *_name;
NSString *_gender;
}
// 挣钱
- (void)makeMoney;
// 做饭
- (void)cook;
// 洗衣服
- (void)washing;
- (NSString *)name;
+ (instancetype)boyWithName:(NSString *)name gender:(NSString *)gender;
@end
Boy.m
#import "Boy.h"
@implementation Boy
- (instancetype)initWithName:(NSString *)name gender:(NSString *)gender{
if ([super init]) {
_name = name;
_gender = gender;
}
return self;
}
// 男孩实现女孩协议中的方法
// 挣钱
- (void)makeMoney{
NSLog(@"%@,我挣了500亿秘鲁币",_name);
}
// 做饭
- (void)cook{
NSLog(@"%@,快来吃饭!",_name);
}
// 洗衣服
- (void)washing{
NSLog(@"%@,我帮你洗白白",_name);
}
- (NSString *)name{
return _name;
}
+ (instancetype)boyWithName:(NSString *)name gender:(NSString *)gender{
return [[Boy alloc] initWithName:name gender:gender];
}
@end
Girl.h
#import <Foundation/Foundation.h>
@protocol YueFa <NSObject>
@required // 使用@required修饰的方法是必须实现的方法,也是默认的状态
// 挣钱
- (void)makeMoney;
// 做饭
- (void)cook;
@optional // 使用@optional修饰的方法,可以选择性的实现
// 洗衣服
- (void)washing;
@end
@interface Girl : NSObject
{
NSString *_name;
NSString *_gender;
// 声明一个代理实例变量
id <YueFa>_delegated;
}
// 给代理实例变量添加一个setter方法,就将那个宗儒的代理商:lol设置进实例变量中
- (void)setDelegated:(id <YueFa>)delegated;
- (NSString *)name;
+ (instancetype)girlWithName:(NSString *)name gender:(NSString *)gender;
// 宗儒饿了
- (void)hungry;
// 宗儒穷了
- (void)poor;
@end
Girl.m
#import "Girl.h"
@implementation Girl
-(instancetype)initWithName:(NSString *)name gender:(NSString *)gender{
if (self =[super init]) {
_gender = gender;
_name = name;
}
return self;
}
- (NSString *)name{
return _name;
}
+ (instancetype)girlWithName:(NSString *)name gender:(NSString *)gender{
return [[Girl alloc]initWithName:name gender:gender];
}
// 实现_delegated的setter方法
- (void)setDelegated:(id<YueFa>)delegated{
_delegated = delegated;
}
// 宗儒饿了
- (void)hungry{
NSLog(@"我饿了!");
// 女孩饿了,有代理去做饭
[_delegated cook];
}
// 宗儒穷了
- (void)poor{
NSLog(@"我穷了");
[_delegated makeMoney];
}
@end