• iOS.常用设计模式.02.委托模式


    WTDelegate
    #import <Foundation/Foundation.h>
    
    @protocol WTDelegate <NSObject>
    
    @required
    
    - (void)sleep;
    
    - (void)eat;
    
    - (void)work;
    
    @end
    WTPhilosopher.h
    #import <Foundation/Foundation.h>
    #import "WTDelegate.h"
    
    @interface WTPhilosopher : NSObject
    {
        NSTimer *timer;
        int count;
    }
    @property (nonatomic,weak) id<WTDelegate> delegate;
    
    - (void)start;
    
    - (void)handle;
    
    @end
    WTPhilosopher.m
    #import "WTPhilosopher.h"
    
    @implementation WTPhilosopher
    @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;
                
            default:
                break;
        }
    }
    
    @end
    WTViewController.m
    #import "WTViewController.h"
    #import "WTPhilosopher.h"
    
    @interface WTViewController ()
    
    @end
    
    @implementation WTViewController
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        
        WTPhilosopher *philosopher = [[WTPhilosopher alloc] init];
        philosopher.delegate = self;
        [philosopher start];
    }
    
    - (void)didReceiveMemoryWarning
    {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    #pragma -- WTDelegate 方法实现
    -(void) sleep
    {
        NSLog(@"sleep...");
    }
    
    -(void) eat
    {
        NSLog(@"eat...");
    }
    
    -(void) work
    {
        NSLog(@"work...");
    }
    
    @end
  • 相关阅读:
    第一次作业
    第一次作业
    第一次作业
    第一次作业
    随笔初谈
    第一次作业
    第一次作业
    第一次班级作业
    C语言感想---第一次作业
    C语言入门
  • 原文地址:https://www.cnblogs.com/cqchen/p/3775844.html
Copyright © 2020-2023  润新知