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>
相关推荐
闲不住的李先森4 分钟前
乐观更新
前端·react.js·设计模式
笔尖的记忆11 分钟前
【前端架构和框架】react组件化&数据流
前端·面试
zhangzelin88819 分钟前
TypeScript入门指南:JavaScript的类型化超集
前端·javascript·其他·typescript
lichenyang45327 分钟前
流式聊天界面实现解析:从零到一构建实时对话体验
前端
天蓝色的鱼鱼27 分钟前
Turbopack vs Webpack vs Vite:前端构建工具三分天下,谁将胜出?
前端·webpack
软件技术NINI38 分钟前
html css js网页制作成品——化妆品html+css+js (7页)附源码
javascript·css·html
用户8417948145639 分钟前
vxe-table 实现列头授权自定义插槽模板,自定义输入框
前端
im_AMBER43 分钟前
Web 开发 24
前端·笔记·git·学习
小小前端_我自坚强1 小时前
前端算法相关详解
前端·算法
小小前端_我自坚强1 小时前
UniApp 微信小程序流水线发布全流程
前端·架构