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>
相关推荐
晚星star1 分钟前
2.2 Node的模块实现
前端·node.js
zYear2 分钟前
Three.js 入门指南:揭开 3D 网页的魔法面纱
前端
Crystal3284 分钟前
图片懒加载
前端·javascript·代码规范
想学后端的前端工程师11 分钟前
【Java设计模式实战应用指南:23种设计模式详解】
java·开发语言·设计模式
Revol_C19 分钟前
开箱即用!轻量级轮询方案,支持同步获取轮询结果!
前端·javascript·设计模式
38242782733 分钟前
python:正则表达式
前端·python·正则表达式
用户479492835691540 分钟前
我是怎么把模型回复用tts播放的更自然的
前端
JS_GGbond40 分钟前
前端崩溃监控:给网页戴上“生命体征监测仪”
前端
俊劫41 分钟前
AI 编码技巧篇(内部分享)
前端·javascript·ai编程
Maxkim42 分钟前
一文读懂 Chrome CRX📦:你需要了解的核心知识点
前端·前端工程化