美文网首页
观察者模式

观察者模式

作者: Carson_Zhu | 来源:发表于2018-02-13 01:43 被阅读10次

观察者模式是为了解决什么问题

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

iOS中解决方案

  • Notification
  • KVO

具体实现

Notification
  • 观察者
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notice:) name:@"notice" object:nil];

- (void)notice:(NSNotification *)sender{  
  NSLog(@"%@",sender);
}

- (void)dealloc {
  // 删除根据name和对象,如果object对象设置为nil,则删除所有叫name的,否则便删除对应的
  [[NSNotificationCenter defaultCenter] removeObserver:self name:@"notice" object:nil];
}
  • 主题对象
/*
 * name     : 通知的名称
 * object   : 通知的发布者
 * userInfo : 通知发布者传递给通知接收者的信息内容,字典格式
 */
[[NSNotificationCenter defaultCenter] postNotificationName:@"notice" object:nil userInfo:@{@"info": @"test"}];
KVO

KVO全称叫Key Value Observing,顾名思义就是一种观察者模式用于监听属性的变化。

例子:

@interface Model : NSObject
@property (nonatomic, copy) NSString *score;
@end
@interface ViewController ()

@property (weak, nonatomic) IBOutlet UILabel *label;
@property (nonatomic, strong) Model *model;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.model = [[Model alloc] init];
    // 监听model的score变化
    [self.model addObserver:self forKeyPath:@"score" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:@"label"];
    self.model.score = @"90";
}

- (IBAction)btnAction:(id)sender {
    // 按钮点击改变model的score
    self.model.score = [NSString stringWithFormat:@"%d", arc4random()%101];
}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if (object == self.model && context == @"label") {
        // 将model的变化值赋给label
        self.label.text = change[@"new"];
    }
}

- (void)dealloc {
    // 移除监听
    [self.model removeObserver:self forKeyPath:@"score" context:@"label"];
}

相关文章

  • 11.9设计模式-观察者模式-详解

    设计模式-观察者模式 观察者模式详解 观察者模式在android中的实际运用 1.观察者模式详解 2.观察者模式在...

  • RxJava基础—观察者模式

    设计模式-观察者模式 观察者模式:观察者模式(有时又被称为发布(publish )-订阅(Subscribe)模式...

  • 前端面试考点之手写系列

    1、观察者模式 观察者模式(基于发布订阅模式) 有观察者,也有被观察者。 观察者需要放到被观察者列表中,被观察者的...

  • RxJava 原理篇

    一、框架思想 观察者模式观察者自下而上注入被观察者被观察者自上而下发射事件观察者模式 装饰器模式自上而下,被观察者...

  • 观察者模式

    观察者模式概念 观察者模式是对象的行为模式,又叫作发布-订阅(publish/subscrible)模式。 观察者...

  • 设计模式-观察者模式

    观察者模式介绍 观察者模式定义 观察者模式(又被称为发布-订阅(Publish/Subscribe)模式,属于行为...

  • 观察者模式

    观察者模式 观察者模式的定义 观察者模式(Observer Pattern)也叫做发布订阅模式(Publish/s...

  • iOS设计模式之观察者模式

    观察者模式 1、什么是观察者模式 观察者模式有时又被称为发布(publish)-订阅(Subscribe)模式、模...

  • 观察者模式和发布订阅模式区别

    观察者模式 所谓观察者模式,其实就是为了实现松耦合(loosely coupled)。 在观察者模式中,观察者需要...

  • RxJava(二)

    一、观察者模式 1.1、传统的观察者模式 1.2、RxJava 的观察者模式 区别传统的观察者模式是一个 Obse...

网友评论

      本文标题:观察者模式

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