web前端全系列 教程
1839个小节阅读:2243.9k
目录
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
状态模式(State)允许⼀个对象在其内部状态改变的时候改变它的⾏为,对象看起来似乎修改了它的类。
xxxxxxxxxx
631<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8">
5 <title>state-demo</title>
6</head>
7<body>
8 <button id="btn">开关</button>
9 <script>
10 // 定义⼀个关闭状态的类
11 class OffLightState {
12 constructor(light) {
13 this.light = light
14 }
15 // 每个类都需要这个⽅法,在不同状态下按都需要触发这个⽅法
16 pressBtn() {
17 this.light.setState(this.light.weekLightState)
18 console.log('开启弱光')
19 }
20 }
21 // 定义⼀个弱光状态的类
22 class WeekLightState {
23 constructor(light) {
24 this.light = light
25 }
26 pressBtn() {
27 this.light.setState(this.light.strongLightState)
28 console.log('开启强光')
29 }
30 }
31 // 定义⼀个强光状态的类
32 class StrongLightState {
33 constructor(light) {
34 this.light = light
35 }
36 pressBtn() {
37 this.light.setState(this.light.offLightState)
38 console.log('关闭电灯')
39 }
40 }
41 class Light {
42 constructor() {
43 this.offLightState = new OffLightState(this)
44 this.weekLightState = new WeekLightState(this)
45 this.strongLightState = new StrongLightState(this)
46 this.currentState = null
47 }
48 setState(newState) {
49 this.currentState = newState
50 }
51 init() {
52 this.currentState = this.offLightState
53 }
54 }
55 let light = new Light()
56 light.init()
57 var btn = document.getElementById('btn')
58 btn.onclick = function() {
59 light.currentState.pressBtn()
60 }
61 </script>
62</body>
63</html>