古代希腊有个哲学家,他毕生只做三件事:“吃饭”“睡觉”“工作”。为了更好的生活,提高工作的效率,他决定找个徒弟,把这些事委托给徒弟做。然而要成为他的徒弟,需要实现一个协议,协议要求能够处理睡觉,吃饭,工作这三件事,
这里面涉及到三个对象:
第一: 哲学家 对应一个通用类 Philospher
第二: 协议 对应一个PhilospherDelegate 规定了三种方法 sleep eat work
第三: 徒弟 对应一个委托对象 ViewController
委托协议 :PhilospherDelegate.h
@protocol PhilosopherDelegate @required -(void) sleep; -(void) eat; -(void) work; @end
委托协议不需要.m文件 可以定义在 其他的 .h文件中
委托类 ViewController
#import <UIKit/UIKit.h> #import "PhilosopherDelegate.h" @interface ViewController : UIViewController<PhilosopherDelegate> @end
#import "ViewController.h" #import "Philosopher.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; Philosopher *obj = [[Philosopher alloc ] init]; obj.delegate = self; [obj start]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma -- PhilosopherDelegate 方法实现 -(void) sleep { NSLog(@"sleep..."); } -(void) eat { NSLog(@"eat..."); } -(void) work { NSLog(@"work..."); } @end
哲学家 Philosopher
#import "PhilosopherDelegate.h" @interface Philosopher : NSObject { NSTimer *timer; int count; } @property (nonatomic, weak) id<PhilosopherDelegate> delegate; -(void) start; -(void) handle; @end
#import "Philosopher.h" @implementation Philosopher @synthesize delegate; -(void) start { count= 0; timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(handle)userInfo:nil repeats:YES]; } -(void)handle { switch (count) { case 0: [self.delegate sleep]; count++; break; case 1: [self.delegate eat]; count++; break; case 2: [self.delegate work]; [timer invalidate]; break; } } @end
时间: 2024-10-12 02:47:34