关闭

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

标签: ios设计模式
392人阅读 评论(0) 收藏 举报
分类:
定义一个消息类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

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:8438次
    • 积分:200
    • 等级:
    • 排名:千里之外
    • 原创:12篇
    • 转载:1篇
    • 译文:0篇
    • 评论:0条
    文章分类