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

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

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

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

下面代码讲解下:

首先创建一个被观察者

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 天前
设计模式(C++)详解—原型模式(1)
c++·设计模式·原型模式
青草地溪水旁1 天前
设计模式(C++)详解—原型模式(2)
c++·设计模式·原型模式
青草地溪水旁1 天前
设计模式(C++)详解—原型模式(3)
c++·设计模式·原型模式
new_daimond1 天前
设计模式-装饰器模式详解
设计模式·装饰器模式
SamDeepThinking2 天前
用设计模式重构核心业务代码的一次实战
java·后端·设计模式
青草地溪水旁2 天前
设计模式(C++)详解——建造者模式(2)
c++·设计模式·建造者模式
o0向阳而生0o2 天前
102、23种设计模式之装饰器模式(11/23)
设计模式·装饰器模式
宁静致远20212 天前
【C++设计模式】第五篇:装饰器模式
c++·设计模式·装饰器模式
IT灰猫2 天前
C++轻量级配置管理器升级版
开发语言·c++·设计模式·配置管理·ini解析