Single-Case mode:
Simple single Case-
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; };
The Main method $scope. TestMethod = function () { var c = div.getsingle (); var d = div.getsingle (); alert (C==d); };
The above single user needs to know that the Getsingle method is designed for a single case. Now implement a transparent single case
Transparent proxy
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 () {
Use the new method of the single var c = new Div (' ab c '); var d = new Div (' 3 '); Alert (c = = d); };
Improved version of the transparent proxy, the constructor is responsible for Init has the responsible instance. The responsibility is not single and the reusability is poor, the way of using the agent is improved
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 (' 3 '); Alert (c = = d); };
Policy mode
The strategy pattern refers to defining a series of algorithms that encapsulate them. The algorithm is used in a unified 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 (+); Alert (l); };
JavaScript Design Patterns