首頁  >  文章  >  web前端  >  關於js的模板方法模式的解說

關於js的模板方法模式的解說

不言
不言原創
2018-07-14 17:23:011678瀏覽

這篇文章主要介紹了關於js的模板方法模式的講解,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下

* 分離出共同點

function Beverage() {}

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

Beverage.prototype.brew = function() {
	throw new Error('子类必须重写brew方法');
}

Beverage.prototype.pourInCup = function() {
	throw new Error('子类必须重写pourInCup方法');
}

Beverage.prototype.addCondiments = function() {
	throw new Error('子类必须重写addCondiments方法');
}

Beverage.prototype.init = function() {
	this.boilWater();
	this.brew();
	this.pourInCup();
	this.addCondiments();
}

function Coffee() {}

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的原型Coffee没有init方法, 
// 顺着原型链委托给父类的Beverage原型上的init方法
coffee.init();

console.log("-------------------------");

function Tea() {}

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();

以上就是本文的全部內容,希望對大家的學習有所幫助,更多相關內容請關注PHP中文網!

相關推薦:

如何透過Vue.js使用Font Awesome實作小圖示

關於js陣列filter的用法

以上是關於js的模板方法模式的解說的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn