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

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

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

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

下面代码讲解下:

首先创建一个被观察者

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

实现结果

有帮助到你点个赞吧!

相关推荐
小程故事多_8036 分钟前
从Claude Code源码泄露,读懂12个可复用的Agentic Harness设计模式(生产级落地指南)
人工智能·设计模式·aigc·ai编程·harness
We་ct1 天前
JS手撕:函数进阶 & 设计模式解析
开发语言·前端·javascript·设计模式·面试·前端框架
冷小鱼1 天前
设计模式全景指南:23种模式深度解析与Python实现
设计模式
楼田莉子1 天前
设计模式:创建型设计模式简介
服务器·开发语言·c++·设计模式
UrSpecial1 天前
设计模式:观察者模式
观察者模式·设计模式
zhaoshuzhaoshu1 天前
设计模式之结构型设计模式详解
python·设计模式
倒流时光三十年1 天前
重学设计模式 之 流式 Builder 模式(Fluent Builder)
设计模式·流式 builder·fluent builder
IT枫斗者1 天前
AI Agent 设计模式全景解析:从单体智能到分布式协作的架构演进
人工智能·redis·分布式·算法·spring·缓存·设计模式