观察者模式
观察者模式:
- 定义对象间的一对多依赖关系,当一个对象(被观察者/主题)的状态发生变化时,所有依赖于它的对象(观察者)都会自动收到通知并更新。
- 特点:一个主题可以广播消息给多个监听者,适用于事件处理系统、消息订阅等场景。
- 类似于订阅发布,
利用观察者模式实现整个页面始终只有一个视频正在播放。在不改动其他组件的时候,直接修改video组件。
observe:
// 观察者
export const observe = {
inPlay: null,
playVideo(videoRef) {
//暂停之前的video
if (this.inPlay) {
this.inPlay.pause();
}
// 播放新的video
videoRef.value.play();
this.inPlay = videoRef.value;
},
pauseVideo() {
if (this.inPlay) {
this.inPlay.pause();
}
this.inPlay = null;
},
};
video:
<script setup>
import { ref } from "vue";
import { observe } from "./0bserver.js";
const videoRf = ref(null);
// 在管理者中使用,调用观察者进行播放和暂停
const play = () => {
observe.playVideo(videoRf);
};
const pause = () => {
observe.pauseVideo();
};
</script>
<template>
<div>
<video
src="./111773_web.mp4"
style="width: 100px; height: 100px"
ref="videoRf"
></video>
<button @click="play">播放</button>
<button @click="pause">暂停</button>
</div>
</template>
单例模式例子
项目在浏览器端使用request,在app端使用requestApp,
要根据不同的场景使用不同的请求
使用单例模式处理单例模式:
//判断环境的方法
const isApp =()=>{
return 'xxx'
}
---------------------
import requestH5 from ""
import requestApp from ""
// 暴露一个标记,通过标记来储存已经实例化的对象
//单例模式保证,某一类只被创建一次
let requestFn = null
export const request =()=>{
if(!requestFn){
// 第一次发请求,要判断登入的环境
if(isApp){
requestFn = requestApp
}else{
requestFn = requestHe
}
requestFn()
}