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>
相关推荐
卖报的小行家_几秒前
读《Vue.js设计与实现》第四章·响应系统的作用与实现
前端
七月丶2 分钟前
🚀 前端缓存踩坑指南:如何优雅地解决浏览器缓存问题?
前端
沉默王二3 分钟前
更快更强!字节满血版DeepSeek在IDEA中真的爽!
java·前端·程序员
木卯6 分钟前
5种创建型设计模式笔记(Python实现)
python·设计模式
掘金酱9 分钟前
👏 用idea传递无限可能!AI FOR CODE挑战赛「创意赛道」作品提交指南
前端·人工智能·trae
Hamm11 分钟前
咦,你的Git仓库贡献者里怎么有这么多大佬???
前端·git·github
潜龙在渊灬28 分钟前
前端 UI 框架发展史
javascript·vue.js·react.js
陈卓41044 分钟前
Redis-限流方案
前端·redis·bootstrap
顾林海1 小时前
Flutter Dart 运算符全面解析
android·前端
七月丶1 小时前
🚀 现代 Web 开发:如何优雅地管理前端版本信息?
前端