<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const OffLightState = function (light) {
this.light = light
}
OffLightState.prototype.buttonWasPressed = function () {
console.log('OffLightState');
this.light.setState(this.light.weakLightState)
}
const WeakLightState = function (light) {
this.light = light
}
WeakLightState.prototype.buttonWasPressed = function () {
console.log('WeakLightState');
this.light.setState(this.light.strongLightState)
}
const StrongLightState = function (light) {
this.light = light
}
StrongLightState.prototype.buttonWasPressed = function () {
console.log('strongLightState');
this.light.setState(this.light.offLightState)
}
const Light = function () {
this.offLightState = new OffLightState(this)
this.weakLightState = new WeakLightState(this)
this.strongLightState = new StrongLightState(this)
this.button = null
}
Light.prototype.init = function () {
const button = document.createElement('button')
self = this
this.button = document.body.appendChild(button)
this.button.innerHTML = 'switch'
this.currState = this.offLightState
this.button.onclick = function () {
self.currState.buttonWasPressed()
}
}
Light.prototype.setState = function (newState) {
this.currState = newState
}
const light = new Light()
light.init()
</script>
</body>
</html>
状态模式实例
最新推荐文章于 2022-05-31 23:36:28 发布