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>
相关推荐
NeverSettle_2 分钟前
2025前端网络相关知识深度解析
前端·javascript·http
JarvanMo3 分钟前
Flutter. Draggable 和 DragTarget
前端
堕落年代5 分钟前
小红书JS SDK签名过程
开发语言·javascript·ecmascript
练习时长一年8 分钟前
后端接口防止XSS漏洞攻击
前端·xss
muchu_CSDN10 分钟前
谷粒商城项目-P16快速开发-人人开源搭建后台管理系统
前端·javascript·vue.js
Bye丶L12 分钟前
AI帮我写代码
前端·ai编程
薛定谔的算法14 分钟前
JavaScript队列实现详解:从基础到性能优化
javascript·数据结构·算法
Sui_Network16 分钟前
GraphQL RPC 与通用索引器公测介绍:为 Sui 带来更强大的数据层
javascript·人工智能·后端·rpc·去中心化·区块链·graphql
PuddingSama17 分钟前
Android 高级绘制技巧: BlendMode
android·前端·面试
Cache技术分享20 分钟前
186. Java 模式匹配 - Java 21 新特性:Record Pattern(记录模式匹配)
前端·javascript·后端