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>
相关推荐
kyriewen3 小时前
编辑弹窗点了取消,列表里的数据怎么还是变了?
前端·javascript·人工智能
Karl_fang3 小时前
🥳 再也不用拿起手机抄验证码!我做了一个 Android → Mac 的「验证码接力」工具
前端·macos·ai编程
谭光志4 小时前
如何让 AI 高效工作
前端·后端·ai编程
code2cat5 小时前
【随笔】MCP长任务:查询已经返回,为什么任务还没有完成
javascript·人工智能·后端·mcp
FRing035 小时前
vue2干货总结11(短信验证、登录功能、统一处理错误(响应拦截器)、将token信息存入vuex、vuex持久化处理)
开发语言·前端·javascript·vue.js·vue2
泯泷5 小时前
改一个字,整段都红了?——中文内容差异对比的算法与协议设计
前端·javascript·typescript
再吃一根胡萝卜5 小时前
DSH plugin 开发示例:五种插件形态完整代码整理
前端
afumu6 小时前
免费 API 满地都是,为什么还有人做「让网页 AI 干活」这种东西
javascript·chrome·浏览器
Yk酱228406 小时前
A2UI随笔-demo-01
前端
云起SAAS6 小时前
本地生活同城多商户商城系统源码源码 合伙人分红加区域代理加排队返现
前端·javascript·后端