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

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

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

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

下面代码讲解下:

首先创建一个被观察者

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

实现结果

有帮助到你点个赞吧!

相关推荐
山沐与山1 天前
【设计模式】Python模板方法模式:从入门到实战
python·设计模式·模板方法模式
阿拉斯攀登1 天前
设计模式:责任链模式
设计模式·责任链模式
崎岖Qiu1 天前
【设计模式笔记18】:并发安全与双重检查锁定的单例模式
java·笔记·单例模式·设计模式
阿闽ooo1 天前
单例模式深度解析:从饿汉到懒汉的实战演进
开发语言·c++·笔记·设计模式
阿拉斯攀登1 天前
设计模式:责任链模式(Spring Security)
设计模式·spring security·责任链模式
阿拉斯攀登1 天前
设计模式:责任链模式(springmvc应用)
设计模式·springmvc·责任链模式
阿拉斯攀登1 天前
设计模式:命令模式
设计模式·命令模式
阿闽ooo1 天前
抽象工厂模式实战:用C++打造家具生产系统(附UML图与完整代码)
c++·设计模式·抽象工厂模式·uml
是店小二呀1 天前
DanceGRPO+FLUX:多模态生成强化学习模型的高效
设计模式
明洞日记1 天前
【设计模式手册022】抽象工厂模式 - 创建产品家族
java·设计模式·抽象工厂模式