一天一种设计模式--模板方法模式

107 阅读1分钟

各个子类都有一些相同的行为,也有不同行为。如果相同和不同行为都混在各个子类实现中,这些相同行为会在子类中重复出现。

很好的体现了泛化思想。 对具有同一规律的学习集以外的数据,经过训练的网络也能给出合适的输出,该能力称为泛化能力。

  1. js继承

 var Beverage = function () { }

    Beverage.prototype.boilWater = function () {
        console.log('把水煮沸')
    }

    Beverage.prototype.brew = function () {
        console.log('子类必须重写brew方法')
    }

    Beverage.prototype.pourIncup = function () {
        console.log('子类必须重写pourInCup方法')
    }

    Beverage.prototype.isNeed = function () {       // isNeed 
         console.log('需要判断方法')
     return true;
     }             

    Beverage.prototype.init = function () {
        this.boilWater();
        this.brew();
        if(this.isNeed())
        this.pourIncup();
    }

    var water = function () {

    }
    water.prototype = new Beverage();  //继承

    water.prototype.brew = function () {
        console.log('brew')
    }

    water.prototype.pourIncup = function () {
        console.log('pourIncup')
    }
    
    water.prototype.isNeed =function(){
       console.log('isNeed')
       window.confirm('是否要加糖')
    }
    var war = new water();
    war.init()
    1. water方法继承 Beverage, 把相同的方法放置到Beverage方法中。类似java中的抽象类。
    1. 模板方法就是做一类事,把共同方法统一封装到父级。并且子类必须实现父类抽象方法。
    1. 也可以利用子类方法(如 重写isNeed )来控制父类 init发生的事件。
  1. 一定需要继承嘛?

不一定 函数式编程


var Beverage = function (param) {
        var todoOne = param.todoOne || function () {
            console.log('todoOne')
        }
        var todoTwo = param.todoTwo || function () {
            console.log('todoTwo')
        }
        var todoThree = param.todoThree || function () {
            console.log('todoThree')
        }
        var init = function () {
            todoOne();
            todoTwo();
            todoThree();
        }
        return {
            init
        }
    }
    var water = {
        todoOne: function () {
            console.log('todoOne--todoOne')
        },
        todoTwo: function () {
            console.log('todoTwo--todoTwo')
        },
        todoThree: function () {
            console.log('todoThree--todoThree')
        }
    }
    var tea = {
        todoOne: function () {
            console.log('teaOne--teaOne')
        },
        todoTwo: function () {
            console.log('teaTwo--teaTwo')
        },
        todoThree: function () {
            console.log('teaThree--teaThree')
        }
    }
    var todo = Beverage(water)
    todo.init()

    var todo2 = Beverage(tea)
    todo2.init()

javaScript 设计模式与开发实践