JavaScript设计模式--模板方法模式

JavaScript设计模式–模板方法模式

一、定义

模板方法是基于继承的设计模式,可以很好的提高系统的扩展性。 java中的抽象父类、子类
模板方法有两部分结构组成,第一部分是抽象父类,第二部分是具体的实现子类。

二、示例

Coffee or Tea
(1) 把水煮沸
(2) 用沸水浸泡茶叶
(3) 把茶水倒进杯子
(4) 加柠檬

/* 抽象父类:饮料 */
var Beverage = function(){};
// (1) 把水煮沸
Beverage.prototype.boilWater = function() {
    console.log("把水煮沸");
};
// (2) 沸水浸泡
Beverage.prototype.brew = function() {
    throw new Error("子类必须重写brew方法");
};
// (3) 倒进杯子
Beverage.prototype.pourInCup = function() {
    throw new Error("子类必须重写pourInCup方法");
};
// (4) 加调料
Beverage.prototype.addCondiments = function() {
    throw new Error("子类必须重写addCondiments方法");
};

/* 模板方法 */
Beverage.prototype.init = function() {
    this.boilWater();
    this.brew();
    this.pourInCup();
    this.addCondiments();
} 

/* 实现子类 Coffee*/
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(); 

通过模板方法模式,在父类中封装了子类的算法框架。这些算法框架在正常状态下是适用大多数子类的,但也会出现“个性”子类。
如上述流程,加调料是可选的。
钩子方法可以解决这个问题,放置钩子是隔离变化的一种常见手段。

/* 抽象父类:饮料 */
var Beverage = function(){};
// (1) 把水煮沸
Beverage.prototype.boilWater = function() {
   console.log("把水煮沸");
};
// (2) 沸水浸泡
Beverage.prototype.brew = function() {
   throw new Error("子类必须重写brew方法");
};
// (3) 倒进杯子
Beverage.prototype.pourInCup = function() {
   throw new Error("子类必须重写pourInCup方法");
};
// (4) 加调料
Beverage.prototype.addCondiments = function() {
   throw new Error("子类必须重写addCondiments方法");
};
/* 添加钩子方法 */
Beverage.prototype.customerWantsCondiments = function() {
   return true;
};
Beverage.prototype.init = function() {
   this.boilWater();
   this.brew();
   this.pourInCup();
   if(this.customerWantsCondiments()) {
       this.addCondiments();
   }
} 

/* 实现子类 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("加牛奶");
};
Tea.prototype.customerWantsCondiments = function() {
   return window.confirm("需要添加调料吗?");
};
var tea = new Tea();
tea.init(); 

JavaScript没有提供真正的类式继承,继承是通过对象与对象之间的委托来实现的。

三、“好莱坞原则”:别调用我们,我们会调用你

典型使用场景:
(1)模板方法模式:使用该设计模式意味着子类放弃了对自己的控制权,而是改为父类通知子类。作为子类,只负责提供一些设计上的细节。
(2)观察者模式:发布者把消息推送给订阅者。
(3)回调函数:ajax异步请求,把需要执行的操作封装在回调函数里,当数据返回后,这个回调函数才被执行。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值