美文网首页
行为型之七-观察者模式

行为型之七-观察者模式

作者: iOS_肖晨 | 来源:发表于2017-10-09 09:28 被阅读3次

    Observer(观察者模式)

    定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态发生变化时,会通知所有观察者对象,使它们能够自动更新自己。

    iOS中的KVO、NSNotication都是观察者模式。

    VC.m

    HCDSubject *subject = [[HCDSecreteSubject alloc]init];
    //添加三个通知对象
    HCDObserver nbaobserver = [[HCDNBAObserver alloc]init];
    [subject attach:nbaobserver];
    HCDObserver stockobserver = [[HCDStockObserver alloc]init];
    [subject attach:stockobserver];
    HCDObserver stockobserver1 = [[HCDStockObserver alloc]init];
    [subject attach:stockobserver1];
    //删除一个通知对象
    [subject detach:stockobserver];
    
    [subject notify];
    

    HCDObserver.h

    @protocol HCDObserver <NSObject>
    @optional
    -(void)update;
    @end
    

    HCDSubject.h

    @interface HCDSubject : NSObject
    -(void)attach:(id<HCDObserver>)observer;
    -(void)detach:(id<HCDObserver>)observer;
    -(void)notify;
    -(NSArray *)getobserverList;
    @end
    

    HCDSubject.m

    @interface HCDSubject ()
    @property(nonatomic,readwrite,strong)NSMutableArray *observerList;
    @end
    @implementation HCDSubject
    -(instancetype)init{
        self = [super init];
        if (self) {
            _observerList = [NSMutableArray array];
        }
        return self;
    }
    -(void)attach:(id<HCDObserver>)observer{
        [self.observerList addObject:observer];
    }
    -(void)detach:(id<HCDObserver>)observer{
        for (id<HCDObserver> currentObserver in [self getobserverList]) {
            if (currentObserver == observer) {
                [self.observerList removeObject:observer];
            }
        }
    }
    -(NSMutableArray *)getobserverList{
        return [NSMutableArray arrayWithArray:self.observerList];
    }
    -(void)notify{
        
    }
    @end
    

    HCDSecreteSubject.h

    @interface HCDSecreteSubject : HCDSubject
    
    @end
    

    HCDSecreteSubject.m

    @implementation HCDSecreteSubject
    -(void)notify{
        NSLog(@"秘书通知:老板回来了,大家赶紧撤");
        for (id<HCDObserver> observer in [self getobserverList]) {
            [observer update];
        }
    }
    @end
    

    设计图

    相关文章

      网友评论

          本文标题:行为型之七-观察者模式

          本文链接:https://www.haomeiwen.com/subject/ebeuyxtx.html