设计模式系列之--观察者模式-画图讲解

观察者模式已经是比较常见的设计模式了,并且使用的频率也比较高,

那么我们什么时候用,简而言之就是,当我们一个主体改变,它所有下级要跟着改变的时候就需要用了,比如:换肤,全局数据修改,有点类似于全局状态机,只不过它可以监听改变的过程。

下面以一张图简单了解下:

下面代码讲解下:

首先创建一个被观察者

javascript 复制代码
  constructor(){
    this.observerList = []
  }
  addObserver(observer){
    this.observerList.push(observer)
  }
  removeObserver(observer){
    const index = this.observerList.findIndex((item)=>item.name === observer.name)
    this.observerList.splice(index,1)
  }
  notifyObservers(message){
    const observers = this.observerList
    observers.forEach(item => {
      item.notified(message)
    });
  }
}

创建观察者

javascript 复制代码
class Observer{
  constructor(name,Subject){
    this.name = name
    if(Subject){
      Subject.addObserver(this)
    }
  }
  notified(message){
    console.log(this.name,message )
  }
}

配合使用

javascript 复制代码
const subject = new Subject()
const observer = new Observer('观察者1号',subject) // 加入观察者
const observer2 = new Observer('观察者2号')
subject.addObserver(observer2)// 加入观察者
subject.notifyObservers('起飞了')`

实现结果

有帮助到你点个赞吧!

相关推荐
繁华似锦respect33 分钟前
单例模式出现多个单例怎么确定初始化顺序?
java·开发语言·c++·单例模式·设计模式·哈希算法·散列表
繁华似锦respect1 小时前
C++ 内存分配器-allocator
开发语言·c++·设计模式
Zaralike1 小时前
Java设计模式
java·开发语言·设计模式
开心香辣派小星3 小时前
23种设计模式-14迭代器模式
设计模式·迭代器模式
2301_803554525 小时前
Pimpl(Pointer to Implementation)设计模式详解
c++·算法·设计模式
__万波__5 小时前
二十三种设计模式(七)--桥接模式
设计模式·桥接模式
老朱佩琪!5 小时前
在Unity中实现状态机设计模式
开发语言·unity·设计模式
达斯维达的大眼睛6 小时前
常用设计模式总结
设计模式
老朱佩琪!6 小时前
Unity建造者设计模式
设计模式
繁华似锦respect6 小时前
C++ 智能指针设计模式详解
服务器·开发语言·c++·设计模式·visual studio