OC-代理设计模式

本文探讨了如何通过实现主协议、子类和定时器,使用Objective-C编程语言自动化照料儿童的过程,包括清洁和情绪调节。


下面实现代码!


#import <Foundation/Foundation.h>
#import "protocoldemo.h"
#import "Children.h"
#import "Jones.h"


int main(int argc, const char * argv[]) {

    //初始化对象
    Jones *jones = [[Jones alloc] init];
    //创建对象 叫Jones去为这个小孩服务
    Children *children = [[Children alloc] initChildren:jones];
    
    //设置小孩
    [jones setChidren:children];
    
    [[NSRunLoop currentRunLoop] run];
    
    
    return 0;
}


//主协议
@protocol protocoldemo <NSObject>

@required

//照护小孩清洁方法
-(void)ChildClean;

//招呼小孩高兴方法
-(void)lowHappy;

@end


#import <Foundation/Foundation.h>
#import "protocoldemo.h"
@interface Children : NSObject

//设置代理对象 不管是那个对象 要想照护小孩必须实现这个协议!
@property(nonatomic,retain) id<protocoldemo> delegate;

//高兴
@property(nonatomic,assign) int happy;
//清洁
@property(nonatomic,assign) int clean;

//初始化对象的时候传入实现这个协议的对象
-(instancetype)initChildren:(id<protocoldemo>) delegate;

-(void)ActionInit:(NSTimer*)timer;

@end


#import "Children.h"

@implementation Children


//初始化对象
-(instancetype)initChildren:(id<protocoldemo>)delegate
{
    if (self = [super init])
    {
        
        self->_delegate = delegate;
      
        self->_clean = 100;
        self->_happy = 100;
        
        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(ActionInit:) userInfo:nil repeats:true];
    };

    return self;
};

-(void)ActionInit:(NSTimer *)timer
{
    self->_happy--;
    self->_clean--;
    
    if(self->_happy <= 90)
    {
        //小孩不高兴了
        [self->_delegate lowHappy];
    };
    
    if (self->_clean <=85) {
        //小孩需要清理了
        [self->_delegate ChildClean];
    }
    
    NSLog(@"高兴值%d",_happy);
    NSLog(@"清洁值%d",_clean);
    
};

#import <Foundation/Foundation.h>
#import "protocoldemo.h"
#import "Children.h"

//实现照护小孩的方法
@interface Jones : NSObject <protocoldemo>
//创建对象属性
@property(nonatomic,retain) Children *chidren;


@end

#import "Jones.h"

@implementation Jones

-(void)ChildClean
{
    NSLog(@"小孩清洁了");
    self->_chidren.clean = 100;
}

-(void)lowHappy
{
    NSLog(@"小孩高新了");
    self->_chidren.happy = 100;
}

@end


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值