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

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

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

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

下面代码讲解下:

首先创建一个被观察者

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('起飞了')`

实现结果

有帮助到你点个赞吧!

相关推荐
小温冲冲19 小时前
通俗且详细讲解模板方法模式
设计模式·模板方法模式
reddingtons1 天前
Magnific AI:拒绝“马赛克”?AI 幻觉重绘流,拯救 1024px 废片
图像处理·人工智能·设计模式·新媒体运营·aigc·设计师·教育电商
知无不研1 天前
c++的设计模式(常用)
c++·观察者模式·单例模式·设计模式·简单工厂模式
李广坤1 天前
设计模式的本质:隔离变化
后端·设计模式
河码匠1 天前
设计模式之依赖注入(Dependency Injection)
java·设计模式·log4j
小湘西1 天前
互联网黑话持续更新
其他·设计模式
a3535413821 天前
设计模式——访问者模式
设计模式·访问者模式
Eloudy1 天前
动态库中不透明数据结构的设计要点总结
数据结构·设计模式
mCell2 天前
为什么 Memo Code 先做 CLI:以及终端输入框到底有多难搞
前端·设计模式·agent
阿里巴巴淘系技术团队官网博客2 天前
设计模式Trustworthy Generation:提升RAG信赖度
人工智能·设计模式