js设计模式——5.状态模式

时间:2020-12-09 07:55:50

js设计模式——5.状态模式

  js设计模式——5.状态模式

js设计模式——5.状态模式

代码演示

/*js设计模式——状态模式*/

// 状态(红灯,黄灯,绿灯)
class State {
constructor(color) {
this.color = color;
} handle(context) {
console.log(`turn to ${this.color} light`);
context.seState(this);
}
} // 主体
class Context {
constructor() {
this.state = null;
} getState() {
return this.state;
} seState(state) {
this.state = state;
}
} // test
let context = new Context()
let green = new State('green')
let yellow = new State('yellow')
let red = new State('red') // 绿灯亮了
green.handle(context)
console.log(context.getState()) // 红灯亮了
red.handle(context)
console.log(context.getState()) // 黄灯亮了
yellow.handle(context)
console.log(context.getState())

js设计模式——5.状态模式

js设计模式——5.状态模式

引入javascript-state-machine示例

/*有限状态机*/
import StateMachine from 'javascript-state-machine'
import $ from 'jquery' let fsm = new StateMachine({
init: '收藏', // 初始化状态,带收藏
transitions : [
{
name : 'doState',
form : '收藏',
to : '取消收藏'
},
{
name : 'deleteState',
form : '取消收藏',
to : '收藏'
}
],
methods : {
// 执行收藏
onDoState : function () {
alert('收藏成功')
updateText()
}, // 取消收藏
onDeleteState: function () {
alert('已取消收藏')
updateText()
}
}
}) let $btn = $('btn1') $btn.click(function () {
if(fsm.is('收藏')){
fsm.doState()
} else {
fsm.deleteState()
}
}) // 更新方案
function updateText() {
$btn.text(fsm.state)
}
// 初始化方案
updateText()

以promise示例来演示

// promise 状态机模型
import StateMachine from 'javascript-state-machine'; let prmiseFsm = new StateMachine({
init: 'pending', // 初始化状态
transitions: [
{
name: 'resolve',
from: 'pending',
to: 'fullfilled',
},
{
name: 'reject',
from: 'pending',
to: 'rejected',
},
],
methods: {
// 监听 resolve
onResolve: function (state, data) {
// state —— 当前状态机示例 data - fsm.resolve(xxx) 传递的参数
data.succesList.forEach(fn => fn())
}, // 监听 reject
onReject: function (state, data) {
// state —— 当前状态机示例 data - fsm.reject(xxx) 传递的参数
data.failList.forEach(fn => fn())
}, },
}); // 定义 Promise
class MyPromise {
constructor(fn) {
this.succesList = []
this.failList = [] fn(function () {
// resolve 函数
fsm.resolve(this)
}, function () {
// reject 函数
fsm.reject(this)
});
} then(succesFn, failFn) {
this.succesList.push(succesFn)
this.failList.push(failFn)
}
} // 测试代码
function loadImg(src) {
const promise = new Promise(function (resolve, reject) {
let img = document.createElement('img');
img.onload = function () {
resolve(img);
};
img.onerror = function () {
reject();
};
img.src = src;
});
return promise;
} let src = 'http://img2.imgtn.bdimg.com/it/u=234634259,4236876085&fm=26&gp=0.jpg';
let result = loadImg(src); result.then(function () {
console.log('ok1');
}, function () {
console.log('fail1');
}); result.then(function () {
console.log('ok2');
}, function () {
console.log('fail2');
});