《JavaScript设计模式与开发实践》读书笔记之模板方法模式

1. 模板方法模式

1.1 面向对象方式实现模板方法模式

以泡茶和泡咖啡为例,可以整理为下面四步

  • 把水煮沸
  • 用沸水冲泡饮料
  • 把饮料倒进杯子
  • 加调料

首先创建一个抽象父类来表示泡一杯饮料

var Beverage=function(){};

Beverage.prototype.boilWater=function(){

    console.log('把水煮沸');

};

Beverage.prototype.brew=function(){};//空方法,由子类重写

Beverage.prototype.pourInCup=function(){};//空方法,由子类重写

Beverage.prototype.addCondiments=function(){};//空方法,由子类重写

Beverage.prototype.init=function(){

    this.boilWater();

    this.brew();

    this.pourInCup();

    this.addCondiments();

};

接下来创建Coffee子类和Tea子类

var Coffee=function(){};

Coffee.prototype=new Beverage();

重写父类的抽象方法

Coffee.prototype.brew=function(){

    console.log('用沸水冲泡咖啡');

};

Coffee.prototype.pourInCup=function(){

    console.log('把咖啡倒进杯子');

};

Coffee.prototype.addCondiments=function(){

    console.log('加糖和牛奶');

};

var Coffee=new Coffee();

Coffee.init();

继续创建Tea类

var Tea=function(){};

Tea.prototype=new Beverage();

Tea.prototype.brew=function(){

    console.log('用沸水浸泡茶叶');

};

Tea.prototype.pourInCup=function(){

    console.log('把茶倒进杯子');

};

Tea.prototype.addCondiments=function(){

    console.log('加柠檬');

};

var tea=new Tea();

tea.init();

上例中,Beverage.prototype.init是模板方法,方法中封装了子类的算法框架
它作为一个算法的模板,指导子类以何种顺序去执行哪些方法

1.2 Javascript中的模板方法模式

var Beverage=function(param){

    var boilWater=function(){

        console.log('把水煮沸');

    };

    var brew=param.brew||function(){

        throw new Error('必须传递brew方法');

    };

    var pourInCup=param.pourInCup||function(){

        throw new Error('必须传递pourInCup方法');

    };

    var addCondiments=param.addCondiments||function(){

        throw new Error('必须传递addCondiments方法');

    };

    var F=function(){};

    F.prototype.init=function(){

        boilWater();

        brew();

        pourInCup();

        addCondiments();

    };

    return F;

};



var Coffee=Beverage(

    {

        brew:function(){

            console.log('用沸水冲泡咖啡');

        },

        pourInCup:function(){

            console.log('把咖啡倒进杯子');

        },

        addCondiments:function(){

            console.log('加糖和牛奶');

        }

    }

);



var Tea=Beverage(

    {

        brew:function(){

            console.log('用沸水浸泡茶叶');

        },

        pourInCup:function(){

            console.log('把茶倒进杯子');

        },

        addCondiments:function(){

            console.log('加柠檬');

        }

    }

);



var coffee=new Coffee();

coffee.init();



var tea=new Tea();

tea.init();

你可能感兴趣的:(JavaScript)