状态模式
状态模式「State Pattern」:允许一个对象在其内部状态改变时改变它的行为,对象看起来似乎修改了它的类。状态模式的关键是区分事物内部的状态,事物内部状态的改变往往会带来事物的行为改变
模式动机
实现
// 定义好五种状态点击时的表现形式
const FMS = {
unUpload: {
onClick: function() {
console.info('开始上传')
this.state = FMS.uploading
}
},
uploading: {
onClick: function() {
console.info('暂停上传')
this.state = FMS.pause
}
},
pause: {
onClick: function() {
console.info('继续上传')
this.state = FMS.uploading
}
},
done: {
onClick: function() {
console.info('已上传成功,点击无效')
}
},
failed: {
onClick: function() {
console.info('重新上传')
this.state.uploading
}
}
}
function File() {
this.state = FMS.pause // 初始状态为未上传
}
const file = new File()
// 将 file 的 this 传进去,改状态时需要
button.onclick = function() {
file.state.onClick.call(file)
}小结
优点
缺点
Last updated
Was this helpful?