首页 > 代码库 > Javascript设计模式
Javascript设计模式
单例模式:
简单单例 -
var div = function (name) { this.instance =null; this.name = name; }; div.prototype.getName= function () { alert(this.name); } div.getSingle = function () { if(!this.instance) { this.instance = new div(); } return this.instance; };
// Main方法 $scope.testMethod = function () { var c = div.getSingle(); var d = div.getSingle(); alert(c==d); };
以上单例用户使用时需要知道getSingle方法是为了单例而设计的方法。现在实现一种透明单例
透明代理
var div = (function () { var instance = null; var createDiv = function (html) { if(instance) return instance; this.html = html; this.init(); instance = this; return instance; }; createDiv.prototype.init = function () { var div = document.createElement(‘div‘); div.innerHTML=this.html; document.body.appendChild(div); }; return createDiv; })(); $scope.testMethod = function () {
// 使用 New的方式 使用 单例 var c = new div(‘ab c‘); var d = new div(‘12 3‘); alert(c == d); };
改进版的透明代理, 构造函数即负责init有负责实例。 职责非单一 而且复用性差,使用代理的方式改进
var div = (function () { var createDiv = function (html) { this.html = html; this.init(); }; createDiv.prototype.init = function () { var div = document.createElement(‘div‘); div.innerHTML = this.html; document.body.appendChild(div); }; return createDiv; })(); var divProxy = (function () { var instance=null; return function (html) { if(instance) return instance; instance = new div(html); return instance; } })(); $scope.testMethod = function () { var c = new divProxy(‘ab c‘); var d = new divProxy(‘12 3‘); alert(c == d); };
策略模式
策略模式指的是 定义一系列的算法,把他们封装起来。 算法使用是在一个统一的Context中。
var stratogyA= function () { }; stratogyA.prototype.getSalary = function (salary) { return salary*2; }; var stratogyB= function () { }; stratogyA.prototype.getSalary = function (salary) { return salary*3; }; var context = function (stratogy) { this.strategy=stratogy; }; context.prototype.calculateSalary= function (orgin) { return this.strategy.getSalary(orgin); }; $scope.testMethod = function () { var str = new stratogyA(); var c = new context(str); var l = c.calculateSalary(1000); alert(l); };
Javascript设计模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。