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链式操作
     
    设计原则验证
    发起者于各个处理者进行隔离
    符合开放封闭原则
  • 相关阅读:
    poj 2100 尺取法 一个数字拆成连续数字平方和
    poj 1011 dfs+剪枝
    CF-242-C bfs+stl
    hdu 1297 递推
    poj 2104 划分树模板
    poj 3842 全排列+筛素数+暴力
    hdu 1421 经典dp
    hdu 1069 最长上升子序列变形
    hdu 3496 二维费用的01背包
    nyoj 16 最长上升子序列变形
  • 原文地址:https://www.cnblogs.com/wzndkj/p/11870479.html
Copyright © 2011-2022 走看看