Home  >  Article  >  Web Front-end  >  An explanation of the template method pattern of js

An explanation of the template method pattern of js

不言
不言Original
2018-07-14 17:23:011677browse

This article mainly introduces the explanation of the template method pattern of js. It has a certain reference value. Now I share it with everyone. Friends in need can refer to it

* Separate the common points

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

The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

How to use Font Awesome to implement small icons through Vue.js

About the usage of js array filter

The above is the detailed content of An explanation of the template method pattern of js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn