zoukankan      html  css  js  c++  java
  • JS 设计模式七 -- 模板方法模式

    概念

    模板方法模式是一直昂只需使用继承就可以实现的非常简单的模式。

    模板方法模式由两部分结构组成,第一部分是抽象父类,第二部分是具体实现的子类。

    实现

    模板方法模式一般的实现方式为继承。

    // 体育运动
    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();

  • 相关阅读:
    PTA(Advanced Level)1009.Product of Polynomials
    PTA(Advanced Level)1002.A+B for Polynomials
    PTA(Advanced Level)1065.A+B and C
    PTA(Advanced Level)1046.Shortest Distance
    PTA(Advanced Level)1042.Shuffling Machine
    PTA(Basic Level)1046.划拳
    PTA(Basic Level)1060.爱丁顿数
    PTA(Basic Level)1053.住房空置率
    PTA(Basic Level)1023.组个最小数
    DOM4J熟知
  • 原文地址:https://www.cnblogs.com/gaosirs/p/10750454.html
Copyright © 2011-2022 走看看