js设计模式之状态模式

xml 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>状态模式</title>
</head>
<body>
<button id="btn">开关</button>
<script>
    class OfflightState{
         constructor(light) {
             this.light = light;
         }
         //每个类都需要的这个方法,在不同的状态下按需要触发这个方法
        pressBtn(){
             this.light.setState(this.light.weekLightState);
            console.log("打开弱光")
        }
    }
    class WeekLightState{
        constructor(light) {
            this.light = light;
        }
        pressBtn(){
            this.light.setState(this.light.strongLightState);
            console.log("打开强光")
        }
    }
    class StrongLightState{
        constructor(light) {
            this.light = light;
        }
        pressBtn(){
            this.light.setState(this.light.offlightState);
            console.log("关闭灯光")
        }
    }
    class Light{
        constructor() {
            this.offlightState = new OfflightState(this);
            this.weekLightState = new WeekLightState(this);
            this.strongLightState = new StrongLightState(this);
            this.currentState = null;
        }
        setState(newState){
            this.currentState = newState;
        }
        init(){
            this.currentState=this.offlightState;
        }
    }
    let light = new Light();
    light.init();
    let btn = document.querySelector("#btn");
    btn.onclick=()=>{
        light.currentState.pressBtn();
    }
</script>
</body>
</html>
相关推荐
云水一下12 分钟前
CSS3从零基础到精通(一):前世今生与基础入门
前端·css3
顾凌陵15 分钟前
CSRF&SSRF漏洞攻击的溯源分析与实战
前端·csrf
用户69190268133917 分钟前
JS 初了解:从“网页玩具”到企业级语言的进化
javascript
月月大王的3D日记17 分钟前
Three.js 材质篇(中):从兰伯特到PBR,一篇文章看懂五种光照材质
前端·javascript
且白18 分钟前
leaflet切片变色、地图滤镜逻辑实现 colorfilter
前端·javascript
用户8876654266322 分钟前
Linux 终端入门:新手必须掌握的常用命令和基本思路
前端·操作系统
丷丩29 分钟前
MapLibre GL JS第30课:添加视频
javascript·音视频·gis·mapbox·maplibre gl js
techdashen30 分钟前
拆开任意 Electron 应用:从 Windows 安装包到 Discord 的私有更新协议
javascript·windows·electron
用户1257585243633 分钟前
Vue3 后台框架的网络请求怎么设计?看 XYGo Admin 三套 Axios 实例与拦截器方案
前端
ZengLiangYi37 分钟前
多格式文件解析:JSONL / SQLite / Event Stream
前端·javascript·后端