iOS与设计模式八 :观察者模式

来源:互联网 发布:mac安装jdk1.8 编辑:程序博客网 时间:2024/05/17 02:36
定义一个消息类Subject,其他类向消息类注册自己,当消息类刷新消息时,就会通知每个注册类。
@interface Subject : NSObject{    NSMutableArray *observerArray;  //添加观察者的数组}+ (id)defaultSubject;- (void)subjectAddObserver:(id)observer withReceiveNotiMethod:(NSString *)method; //添加观察者和观察者接收消息的方法- (void)subjectDelObserver:(id)observer;- (void)subjectPostNotificationWithObject:(NSString *)value;  //状态改变,发送通知给观察者@end#import "Subject.h"static Subject *subject;  //这里使用一个单例@implementation Subject+ (id)defaultSubject{    if (!subject) {        subject = [[Subject alloc]init];    }    return subject;}- (id)init{    self = [super init];    if (self) {        observerArray = [[NSMutableArray alloc]init];    }    return self;}- (void)subjectAddObserver:(id)observer withReceiveNotiMethod:(NSString *)method{    NSArray *array = [NSArray arrayWithObjects:observer,method, nil];    BOOL isExist = NO;    for(NSArray *array in observerArray) {        if ([[array objectAtIndex:0] isEqual:observer]) {            isExist = YES;            break;        }    }    if (!isExist) {        [observerArray addObject:array];    }    }- (void)subjectDelObserver:(id)observer{    for(NSArray *array in observerArray)    {        if([[array objectAtIndex:0] isEqual:observer])        {            [observerArray removeObject:observer];            break;        }    }}- (void)subjectPostNotificationWithObject:(NSString *)value{    for(NSArray *array in observerArray)    {        id observer = [array objectAtIndex:0];        SEL selector = NSSelectorFromString([array objectAtIndex:1]);                if ([observer respondsToSelector:selector]) { //如果可以响应这个方法            [observer performSelector:selector withObject:value];        }    }}@interface observerA : NSObject@end@implementation observerA- (void)aMethod            [[Subject defaultSubject] subjectAddObserver:self withReceiveNotiMethod:NSStringFromSelector(@selector(receiveChange:))];    [[Subject defaultSubject] subjectPostNotificationWithObject:@"value"];        }- (void)receiveChange:(NSString *)value{    NSLog(@"%@",value);}@end