zoukankan      html  css  js  c++  java
  • 前端设计模式 模板方法模式和职责链模式

    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链式操作
     
    设计原则验证
    发起者于各个处理者进行隔离
    符合开放封闭原则
  • 相关阅读:
    Leetcode888. 公平的糖果棒交换
    Leetcode81. 搜索旋转排序数组 II
    Leetcode80. 删除排序数组中的重复项 II
    Leetcode1631. 最小体力消耗路径
    Leetcode57. 插入区间
    Leetcode724. 寻找数组的中心索引
    Leetcode18. 四数之和
    Leetcode110. 平衡二叉树
    Leetcode1128. 等价多米诺骨牌对的数量
    python 集合和深浅copy
  • 原文地址:https://www.cnblogs.com/wzndkj/p/11870479.html
Copyright © 2011-2022 走看看