# 04-提高代码质量

# 策略/状态模式

帮助我们优化if-else结构

  • 状态模式: 允许一个对象在其内部状态改变时改变它的行为。对象看起来似乎修改了它的类。
DETAILS
// 示例:权限管理,根据不同权限显示不同菜单
function menuControl(){
    this.status = '';
    this.control = {
        boss: function(){
            showMenu1();
            showMenu2();
            showMenu3();
        },
        manager: funciton(){
            showMenu2();
            showMenu3();
        },
        staff: funciton(){
            showMenu3();
        },
    }
}
mover.prototype.show = funciton(){
   let _this = this;
   axios.get('/url').then(res => {
       _this.status = res.status;
       _this.control[_this.status]();
   });
}
new menuControl().show();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
  • 策略模式:定义一系列的算法,把它们一个个封装起来,并且使它们可互相替换。本模式使得算法可独立于使用它的客户而变化。
DETAILS
function mover(){
    this.status = [];
    this.actionHandler = {
        left: function(){},
        right: funciton(){},
        top: funciton(){},
        bottom: funciton(){},
    }
}
mover.prototype.run = funciton(){
    this.status = Array.prototype.slice.call(arguments);
    this.status.forEach(action =>{
        this.actionHandler[action]();
    });
}
new mover().run('left', 'top');
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 外观模式

一种套餐化接口的思想,提醒我们封装常用的方法

# 迭代器模式

帮助我们更好的遍历数据

# 备忘录模式

帮我们缓存以及回到过去的状态