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>
相关推荐
老码观察几秒前
设计模式实战解读(一):单例模式——全局唯一实例的正确打开方式
单例模式·设计模式
老码观察16 分钟前
设计模式实战解读(二):工厂模式——对象创建的解耦艺术
设计模式·log4j
a11177626 分钟前
动森UI组件(开源 html animal-island-ui )
前端·javascript·ui·开源·html
KaMeidebaby27 分钟前
卡梅德生物技术快报|真核蛋白表达信号肽筛选实验全流程复盘
服务器·前端·数据库·人工智能·算法
ljt272496066128 分钟前
Vue笔记(六)--响应式
javascript·vue.js·笔记
threelab35 分钟前
Three.js 黑洞引力效果着色器 | 三维可视化 / AI 提示词
开发语言·javascript·着色器
万少1 小时前
万少的 Claude Code 入门教程
前端·人工智能·后端
এ慕ོ冬℘゜1 小时前
JS 前端基础高频面试题
开发语言·前端·javascript
放下华子我只抽RuiKe51 小时前
React 从入门到生产(八):测试与部署
前端·javascript·深度学习·react.js·前端框架·ecmascript·集成学习
Dxy12393102161 小时前
JS列表获取指定范围值的 N 种方法
开发语言·javascript·ecmascript