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

定义一个消息类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

阅读更多
文章标签: ios 设计模式
个人分类: iOS与设计模式
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭