码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-07-18 23:59:56      阅读:411      评论:0      收藏:0      [点我收藏+]

标签:

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设计模式与开发实践》读书笔记之模板方法模式

标签:

原文地址:http://www.cnblogs.com/GongQi/p/4657911.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!