前端设计模式 模板方法模式和职责链模式

class Action {
    handle() {
        handle1();
        handle2();
        handle3();
    }
    handle1() {
        console.log('1');    
    }
    handle2() {
        console.log('2');    
    }
    handle3() {
        console.log('3');    
    }
}
模板方法模式:如上,如果代码中有 handle1,handle2,handle3 这几步处理的话,我们可以通过一个方法给他封装起来,调用的话,调用这一个方法就可以。 对于内部有顺序的方法,可以通过一个方法封装起来,暴露给外部。



职责链模式:一步操作可能分为多个职责角色来完成。把这些角色都分开,然后用一个链串起来。将发起者以及各个处理者进行隔离。
比如你要请假,需要审批,需要组长审批,经理审批,最后总监审批
// 请假审批,需要组长审批,经理审批,最后总监审批
class Action {
    constructor(name) {
        this.name = name;
        this.nextAction = null;
    }
    setNextAction(action) {
        this.nextAction = action;
    }
    handle() {
        console.log(`${this.name} 审批`);
        if (this.nextAction != null) {
            this.nextAction.handle();
        }
    }
}

// 测试
let a1 = new Action('组长');
let a2 = new Action('经理');
let a3 = new Action('总监');
a1.setNextAction(a2);
a2.setNextAction(a3);
a1.handle();
应用场景:promise.then链式操作
 
设计原则验证
发起者于各个处理者进行隔离
符合开放封闭原则

猜你喜欢

转载自www.cnblogs.com/wzndkj/p/11870479.html