介绍
- 一个对象有状态的变化
- 每次状态变化都会触发一个逻辑
- 不能总是用
if..else
控制
实例
- 交通信号灯不同颜色的变化
UML类图
image代码演示
class State {
constructor(color) {
this.color = color
}
handle(context) {
console.log('当前是' + this.color + '灯')
context.setState(this)
}
}
class Context{
constructor() {
this.state= null
}
getState(){
return this.state
}
setState(state){
this.state = state
}
}
//test
let context = new Context()
let g = new State('g')
let y = new State('y')
let r = new State('r')
//绿亮
g.handle(context)
context.getState()
//黄亮
y.handle()
context.getState()
//红亮
r.handle()
context.getState()
场景
- 有限状态机
- 简单的
Promise
有限状态机制
- 有限个状态,以及在这些状态之间的变化
- 比如交通信号灯
javascript-state-machine
npm install javascript-state-machine --save
<script src="https://cdn.bootcss.com/javascript-state-machine/2.0.0/state-machine.min.js"></script>
//初始化状态机模型
let fsm = new StateMachine({
init: '收藏',
transactions: [
{
name: 'doStore',
from: '收藏',
to: '取消收藏'
},
{
name: 'deleteStore',
from: '取消收藏',
to: '收藏'
},
],
methods: {
//监听
onDostore: function () {
alert('收藏成功')
updateText()
//other ... ajax
},
onDeleteStore: function () {
alert('取消收藏成功')
updateText()
//other ... ajax
}
}
})
let btn = document.getElementById('btn1')
btn.onclick(function () {
if(fsm.is('收藏')){
fsm.doStore()
}else{
fsm.deleteStore()
}
})
function updateText() {
btn.innerText = fsm.state
}
实现状态变化的Promise
let fsm = new StateMachine({
init: 'pending',
transactions: [
{
name: 'resolve',
from: 'pendinf',
to: 'fullfilled'
},
{
name: 'reject',
from: 'pending',
to: 'rejected'
},
],
methods: {
//监听
//state 当前状态机实例
// data fsm.resolve(xxx) 传递的参数
onResolve: function (state,data) {
data.successList.forEach(fn=>fn())
},
onReject: function (state,data) {
data.failList.forEach(fn=>fn())
}
}
})
class MyPromise{
constructor(fn) {
this.successList = []
this.failList = []
fn(()=>{
//fsm状态机
fsm.resolve(this)
},()=>{
fsm.reject(this)
})
}
then(successFn,failFn){
this.successList.push(successFn)
this.failList.push(failFn)
}
}
代码
原文
https://www.ahwgs.cn/javascriptshejimoshizhizhuangtaimoshi.html
网友评论