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 分钟前
(接上一篇)前端弄一个变量实现点击次数在前端页面实时更新
前端·javascript·vue.js
YANG-Live29 分钟前
数据列表组件-报表
开发语言·javascript
kinlon.liu1 小时前
Web应用安全实用建议
前端·网络·网络协议·安全·centos
narukeu1 小时前
理解 React 的严格模式
前端·javascript·react.js
Bee.Bee.1 小时前
移动端如何调试本地运行的前端项目
前端
Tech Synapse1 小时前
java 如何暴露header给前端
java·开发语言·前端
卓卓没头发1 小时前
掌握Vue插槽:创建灵活且可复用的组件
前端·javascript·vue.js
白臻1 小时前
小程序 npm 支持
前端·小程序·npm
lyllovelemon1 小时前
🍭🍭🍭五分钟带你掌握next国际化最佳实践
前端·react.js·面试
hlyling2 小时前
一键高效处理,批量缩放PNG图片,按比例轻松调整,高效工作从此开始!
javascript·python·c#·objective-c·batch·symfony