一、装饰器模式
介绍
- 顺序访问一个集合
- 使用者无需知道集合的内部结构(封装)




二、状态模式
介绍
- 一个对象又状态变化(如收藏/取消收藏)
- 每次状态变化都会触发一个逻辑
- 不能总是用If...else来控制,尤其在比较的多的情况下

一个切换红黄绿灯的例子


场景一 有限状态机

import StateMachine from 'javascript-state-machine'
import $ from 'jquery'
console.log(StateMachine,333)
//初始化状态机模型
let fsm = new StateMachine({
init:'收藏',
transitions:[
{
name:'doStore',
from:'收藏',
to:'取消收藏'
},
{
name:'deleteStore',
from:'取消收藏',
to:'收藏'
}
],
methods:{
// 监听执行收藏
onDoStore:function () {
alert('收藏成功')
updateText()
},
// 监听执行取消收藏
onDeleteStore:function(){
alert('取消收藏成功')
updateText()
}
}
})
let $btn = $('#btn1')
$btn.click(function(){
if(fsm.is('收藏')){
fsm.doStore()
}else{
fsm.deleteStore()
}
})
//更新按钮的文案
function updateText(){
$btn.text(fsm.state)
}
//初始化文案
updateText()
实现一个Promise




实现一个购物车
效果图

UML类图

代码:https://github.com/zzyo96/JSDesignPatterns/tree/master/demo/shoppingCart
网友评论