iOS与观察者模式(二)

上一篇是对观察者模式的概念上的讨论,这一篇是利用通知来实现观察者模式,错误之处敬请批评指正。

代码示例

在iOS中日常开发中,CocoaTouch框架的 通知KVO 都实现了观察者模式。下面小江简单用两种模式实现下,具体通知和kvo的原理就不在此赘述了,毕竟不是设计模式的重点~

通知实现
//直接写了具体主题角色,偷了懒没有写抽象主题
@interface Bell : NSObject
- (void)attachObserver:(Observer *)observer;
- (void)classBegin;
- (void)classEnd;
@property (nonatomic, strong) NSMutableArray *observers;
@end

@implementation Bell
- (void)attachObserver:(Observer *)observer {
//这里有点照本宣科了,其实ios的通知里并不需要这个方法,这里只是想和类图中的结构保持一致
    [self.observers addObject:observer];
}

- (void)classBegin {
  NSLog(@"上课铃响了");
  NSDictionary *dic = @{@"classBegin":@YES};
  [[NSNotificationCenter defaultCenter] postNotificationName:@"classBellRing" 
                                                       object:self userInfo:dic];
}

- (void)classEnd {
    NSLog(@"下课铃响了");
    NSDictionary *dic = @{@"classBegin":@NO};
    [[NSNotificationCenter defaultCenter] postNotificationName:@"classBellRing" 
                                                        object:self userInfo:dic];
 }
@end

//抽象观察者角色
@interface Observer : NSObject
- (void)update:(NSNotification *)notification;
@end

@implementation Observer
- (id)init {
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(update:) name:@"classBellRing" object:nil];
    }
    return self;
}

- (void)update:(NSNotification *)notification {
   //to be Override...
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:@"classBellRing"];
}
@end

//具体观察者角色
@interface Student : Observer
@end

@implementation Student
- (void)update:(NSNotification *)notification {
    NSDictionary *userInfo =  notification.userInfo;
    if ([[userInfo objectForKey:@"classBegin"] boolValue]) {
        [self classBegin];
    } else {
        [self classEnd];
    }
}

- (void)classBegin {
    NSLog(@"上课了,学生回到教室");
}

- (void)classEnd {
    NSLog(@"下课了,学生离开教室");
}
@end

//主函数调用
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        //观察者模式
        Bell *bell = [[Bell alloc] init];
        Student *stu1 = [[Student alloc] init];
        [bell attachObserver:stu1];
        [bell classBegin];
        [bell classEnd];
    }
    return 0;
}

运行结果:

2017-01-06 23:37:49.022 DesignPattern[3309:91471] 上课铃响了
2017-01-06 23:37:49.023 DesignPattern[3309:91471] 上课了,学生回到教室
2017-01-06 23:37:49.023 DesignPattern[3309:91471] 下课铃响了
2017-01-06 23:37:49.023 DesignPattern[3309:91471] 下课了,学生离开教室
Program ended with exit code: 0

以上,如有问题敬请批评指正~本文系作者原创,转载请注明出处

你可能感兴趣的:(iOS与观察者模式(二))