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

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

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

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

下面代码讲解下:

首先创建一个被观察者

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 天前
Guava 迭代器增强类介绍
java·后端·设计模式
李宥小哥1 天前
创建型设计模式1
stm32·嵌入式硬件·设计模式
李宥小哥1 天前
结构型设计模式2
网络·数据库·设计模式
guangzan1 天前
TypeScript 中的策略模式
设计模式
乐悠小码1 天前
Java设计模式精讲---04原型模式
java·设计模式·原型模式
李宥小哥1 天前
行为型设计模式2
windows·设计模式
Juchecar2 天前
Java示例:设计模式是如何在实战中“自然生长”出来
java·设计模式
Juchecar2 天前
超越经典23种设计模式:新模式、反模式与函数式编程
设计模式·云原生·函数式编程
Juchecar2 天前
设计模式不是Java专属,其他语言的使用方法
java·python·设计模式