JS 設計模式七 -- 模板方法模式

概念

模板方法模式是一直昂只需使用繼承就能夠實現的很是簡單的模式。this

模板方法模式由兩部分結構組成,第一部分是抽象父類,第二部分是具體實現的子類。spa

 

實現

模板方法模式通常的實現方式爲繼承。prototype

// 體育運動
function Sport() {

}

Sport.prototype = {
    constructor: Sport,
    
    // 模板,按順序執行
    init: function() {
        this.stretch();
        this.jog();
        this.deepBreath();
        this.start();

        var free = this.end();
        
        // 運動後還有空的話,就拉伸一下
        if (free !== false) {
            this.stretch();
        }
        
    },
    
    // 拉伸
    stretch: function() {
        console.log('拉伸');
    },
    
    // 慢跑
    jog: function() {
        console.log('慢跑');
    },
    
    // 深呼吸
    deepBreath: function() {
        console.log('深呼吸');
    },

    // 開始運動
    start: function() {
        throw new Error('子類必須重寫此方法');
    },

    // 結束運動
    end: function() {
        console.log('運動結束');
    }
};

// 籃球
function Basketball() {

}

Basketball.prototype = new Sport();

// 重寫相關的方法
Basketball.prototype.start = function() {
    console.log('先投上幾個三分');
};

Basketball.prototype.end = function() {
    console.log('運動結束了,有事先走一步');
    return false;
};


// 馬拉松
function Marathon() {

}

Marathon.prototype = new Sport();

var basketball = new Basketball();
var marathon = new Marathon();

// 子類調用,最終會按照父類定義的順序執行
basketball.init();
marathon.init();

相關文章
相關標籤/搜索