Skip to content

Latest commit

 

History

History
104 lines (89 loc) · 2.53 KB

File metadata and controls

104 lines (89 loc) · 2.53 KB

一. 模板方法模式

父类中定义一组算法操作骨架,而将一些实现步骤延伸到子类中,使得子类在不改变父类算法结构的同时可重新定义算法某些实现步骤。

模板方法模式主要由两部分组成:

  • 抽象父类
  • 具体实现子类

演示

这里我们直接拿网上最常用的例子来举例说明

Coffee or Tea

  • 把水煮沸
  • 用沸水浸泡茶叶
  • 把茶水倒进杯子
  • 加柠檬
/* 抽象父类:饮料 */
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();

通过模板方法模式,在父类中封装了子类的算法框架。这些算法框架在正常状态下是适用大多数子类的,但也会出现“个性”子类。

如上述流程,加调料是可选的。

钩子方法可以解决这个问题,放置钩子是隔离变化的一种常见手段。

/* 添加钩子方法 */
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();