zoukankan      html  css  js  c++  java
  • iOS 委托模式 理解例子

    古代希腊有个哲学家,他毕生只做三件事:“吃饭”“睡觉”“工作”。为了更好的生活,提高工作的效率,他决定找个徒弟,把这些事委托给徒弟做。然而要成为他的徒弟,需要实现一个协议,协议要求能够处理睡觉,吃饭,工作这三件事,

    这里面涉及到三个对象:

    第一: 哲学家  对应一个通用类 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
    

     

  • 相关阅读:
    Java基础-IO流对象之字节流(Stream)
    Java基础-IO流对象之File类
    Java基础-集合的嵌套
    rsync命令的基本使用
    java基础-Map集合
    Java基础-Collection子接口之Set接口
    Java基础-Collection子接口之List接口
    Java基础-泛型
    Unity4.3 bug GetChild顺序错乱
    Windows系统上的.Net版本和.NETFramework的C#版本
  • 原文地址:https://www.cnblogs.com/penger/p/4228303.html
Copyright © 2011-2022 走看看