Home > Article > Web Front-end > How to implement template method singleton in JavaScript
This article mainly introduces the relevant information about the implementation method of template method singleton in javascript. I hope this article can help everyone. Friends in need can refer to
template method singleton in javascript Implementation method of example
Template method singleton
Definition of template method: Define a set of operation algorithm skeleton in the parent class, and extend some implementation steps to In the subclass, the subclass can redefine some implementation steps in the algorithm without changing the algorithm structure of the parent class.
Code block
html part, for example:
<p id="content"></p>
js part, for example:
//格式化字符串方法 function fromateString(str, data) { return str.replace(/\{#(\w+)#\}/g, function(match, key){ return typeof data[key] === undefined ? '' : data[key] }); } //基础导航 var Nav = function (data) { //基础导航样式模板 this.item = '<a href="{#href#}" rel="external nofollow" title="{#title#}">{#name#}</a>'; //创建字符串 this.html=''; for (var i = 0; i < data.length; i++) { this.html += fromateString(this.item, data[i]); } return this.html; } //带有信息提示信息导航 var NumNav = function (data) { //消息提醒小心组件模板 var tpl = '<p>{#num#}</p>'; for (var i = data.length -1; i >= 0; i--) { data[i].name += data[i].name + fromateString(tpl, data[i]); } return Nav.call(this, data); } //带有链接地址的导航 var LinkNav = function (data) { //消息提醒小心组件模板 var tpl = '<span>{#link#}</span>'; for (var i = data.length -1; i >= 0; i--) { data[i].name += data[i].name + fromateString(tpl, data[i]); } return Nav.call(this, data); } //测试带有信息提示的导航 var nav = document.getElementById('content'); nav.innerHTML = NumNav([ { href : 'www.baidu.com', title : '百度一下你就知道', name : '百度', num : 10, link : 'www.baidu.com' }, { href : 'www.taobao.com', title : '淘宝商城', name : '淘宝', num : 2, link : 'www.taobao.com' }, { href : 'www.qq.com', title : '腾讯首页', name : '腾讯', num : 3, link : 'www.qq.com' } ]);
In fact, the template method pattern is not only used when we normalize components, but is also commonly used when creating pages. The above code can derive the encapsulation of static pages and the interactive encapsulation of business logic.
The above is the detailed content of How to implement template method singleton in JavaScript. For more information, please follow other related articles on the PHP Chinese website!