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>
相关推荐
半生过往8 分钟前
前端学 Java 课程笔记
java·前端·笔记
广州华水科技44 分钟前
2026年单北斗GNSS变形监测系统推荐,破解水库安全监测难题
前端
独爱香菜1 小时前
Next.js 15 + Cloudflare Workers 实战:零中间件多语言 SEO 站点架构
前端
计算机魔术师1 小时前
DeepSeek、Qwen3比肩GPT-5,本地跑大模型的时代来了
前端
xcyxiner1 小时前
flutter wsl2安装记录(使用宿主机虚拟机)
前端·flutter
前端炒粉1 小时前
长会话虚拟滚动与渲染优化
前端·javascript·vue.js
谙忆10242 小时前
图片裁剪总是跑偏?用 object-fit、object-position 和真实像素把坐标对齐
javascript·css·图像识别
花归去2 小时前
ant的a-table更改表格的高度
前端·javascript·html
sibylyue2 小时前
基于 Vben Admin 框架的 Vue 3 前端项目配置文件及常用命令
前端·javascript·vue.js
知几蜗牛2 小时前
0 后端 · 0 数据库 · 0 备案:用 AI 两天搓出的股票管理系统,开源了
前端·后端·llm