前端設計模式 模板方法模式和職責鏈模式

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鏈式操做
 
設計原則驗證
發起者於各個處理者進行隔離
符合開放封閉原則
相關文章
相關標籤/搜索