介紹
- 一個(gè)對(duì)象有狀態(tài)變化
- 每次狀態(tài)變化都會(huì)觸發(fā)一個(gè)邏輯
- 不能總是使用if...else來(lái)控制
eg: 紅綠燈 收藏/未收藏
核心: 狀態(tài)和主體分離
UML類圖
代碼演示
class State {
constructor(color) {
this.color = color
}
handle(context) {
console.log(`turn to ${this.color} light`)
context.setState(this)
}
}
class Context {
constructor() {
this.state = null
}
setState(state) {
this.state = state
}
getState() {
return this.state
}
}
// 測(cè)試代碼
let context = new Context()
let greed = new State('greed')
let yellow = new State('yellow')
let red = new State('red')
// 綠燈亮了
greed.handle(context)
console.log(context.getState())
// 黃燈亮了
yellow.handle(context)
console.log(context.getState())
// 紅燈亮了
red.handle(context)
console.log(context.getState())
場(chǎng)景
- 有限狀態(tài)機(jī)
- 寫一個(gè)簡(jiǎn)單的Promise
有限狀態(tài)機(jī)
- 有限個(gè)狀態(tài),以及在這些狀態(tài)間的變化
- 如交通信號(hào)燈
- 使用開源lib :javascript-state-machine
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<p>有限狀態(tài)機(jī)</p>
<button id="btn"></button>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script src="./03-javascript-state-machine.js"></script>
<script>
// 狀態(tài)機(jī)模型
var fsm = new StateMachine({
init: '收藏', // 初始狀態(tài)按咒,待收藏
transitions: [
{
name: 'doStore',
from: '收藏',
to: '取消收藏'
},
{
name: 'deleteStore',
from: '取消收藏',
to: '收藏'
}
],
methods: {
// 執(zhí)行收藏
onDoStore: function () {
alert('收藏成功')
updateText()
},
// 取消收藏
onDeleteStore: function () {
alert('已取消收藏')
updateText()
}
}
})
var $btn = $('#btn')
// 點(diǎn)擊事件
$btn.click(function () {
if (fsm.is('收藏')) {
fsm.doStore(1)
} else {
fsm.deleteStore()
}
})
// 更新文案
function updateText() {
$btn.text(fsm.state)
}
// 初始化文案
updateText()
</script>
</body>
</html>
寫一個(gè)Promise
Promise 三個(gè)狀態(tài)
- pending 準(zhǔn)備
- fullfilled 成功 (執(zhí)行resolve)
- rejected 失敗
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script src="./03-javascript-state-machine.js"></script>
<script>
// 模型
var fsm = new StateMachine({
init: 'pending',
transitions: [
{
name: 'resolve',
from: 'pending',
to: 'fullfilled'
},
{
name: 'reject',
from: 'pending',
to: 'rejected'
}
],
methods: {
// 成功
onResolve: function (state, data) {
// 參數(shù):state - 當(dāng)前狀態(tài)示例; data - fsm.resolve(xxx) 執(zhí)行時(shí)傳遞過來(lái)的參數(shù)
data.successList.forEach(fn => fn())
},
// 失敗
onReject: function (state, data) {
// 參數(shù):state - 當(dāng)前狀態(tài)示例; data - fsm.reject(xxx) 執(zhí)行時(shí)傳遞過來(lái)的參數(shù)
data.failList.forEach(fn => fn())
}
}
})
// 定義 Promise
class MyPromise {
constructor(fn) {
this.successList = []
this.failList = []
fn(() => {
// resolve 函數(shù)
fsm.resolve(this)
}, () => {
// reject 函數(shù)
fsm.reject(this)
})
}
then(successFn, failFn) {
this.successList.push(successFn)
this.failList.push(failFn)
}
}
// 測(cè)試代碼
function loadImg(src) {
const promise = new MyPromise(function (resolve, reject) {
var img = document.createElement('img')
img.onload = function () {
resolve(img)
}
img.onerror = function () {
reject()
}
img.src = src
})
return promise
}
var src = 'http://www.imooc.com/static/img/index/logo_new.png'
var result = loadImg(src)
console.log(result)
result.then(function (img) {
console.log('success 1')
}, function () {
console.log('failed 1')
})
result.then(function (img) {
console.log('success 2')
}, function () {
console.log('failed 2')
})
</script>
</body>
</html>
設(shè)計(jì)原則驗(yàn)證
- 將狀態(tài)對(duì)象和主題對(duì)象分離迟隅,狀態(tài)的變化邏輯單獨(dú)處理
- 符合開放封閉原則
本文資料來(lái)自慕課網(wǎng)-雙越老師-Javascript 設(shè)計(jì)模式系統(tǒng)講解與應(yīng)用視頻課程