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 分钟前
都2025年了,还有面试问A*寻路的???
前端
Moment8 分钟前
Node.js v25.0.0 发布——性能、Web 标准与安全性全面升级 🚀🚀🚀
前端·javascript·后端
杨超越luckly12 分钟前
HTML应用指南:利用POST请求获取中国一汽红旗门店位置信息
前端·arcgis·html·数据可视化·门店数据
专注前端30年17 分钟前
【JavaScript】every 方法的详解与实战
开发语言·前端·javascript
速易达网络19 分钟前
Java Web登录系统实现(不使用开发工具)
java·开发语言·前端
IT_陈寒22 分钟前
Vite 3.0 性能优化实战:5个技巧让你的构建速度提升200% 🚀
前端·人工智能·后端
金士顿25 分钟前
EC-Engineer SDK 核心 API 使用指南
前端
景彡先生38 分钟前
Python基础语法规范详解:缩进、注释与代码可读性
开发语言·前端·python
蓝创精英团队41 分钟前
C++DirectX9坐标系与基本图元之渲染状态(RenderState)_0304
前端·c++·性能优化