简单工厂模式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
|
var Dog = function () {
};
Dog.prototype = {
}
var Cat = function () {
};
Cat.prototype = {
}
var FactoryEasy = function (name) { switch(name){ case 'dog': return new Dog(); case 'cat': return new Cat(); } }
var Factory = function (name) { var o = new Object();
switch(name){ case 'dog': o.name = 'dog' case 'cat': o.name= 'cat' } return 0 }
var Animal = function (name) { this.name = name; }
var Factory = function (name) { let work = '';
switch(name){ case 'dog': work = 'dog' case 'cat': work = 'cat' } return new Animal(work) }
|
工厂模式
适用于创建多类对象,使使用者与类解耦,增加或者减少类不会影响工厂函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
var Factory = function (name,options) { if(this instanceof Factory){ return new this[name](options) }else { return new Factory(name,options) } }
Factory.prototype = { dog:function (options) {
}, cat: function (opstions) {
} }
|
单例模式
一个类只允许实例化一次, 利用闭包保证一个类只被实例化一次
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| var singleObj = (function () { var single = null;
function func() { var a = "aa"; }
return function(){ if(!single){ single = new func() return single; } return single; }
})();
|
装饰者模式
装饰模式 只添加不修改,不改变原有方法功能的情况,增强功能
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
function a() { var a = 111; }
function b() { var b = 222; }
var newa = function () { a(); b(); }
var decorator = function (selector, fn) { var ele = document.querySelector(selector);
if(typeof ele.onclick === 'function'){ var oldfn = ele.onclick;
ele.onclick = function () { oldfn(); fn(); } }else { ele.onclick = fn() } }
|
适配器模式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
function f(options) {
var _adapter = { a: '12', b: 12 }
for (var i in _adapter){ options[i] = options[i] || _adapter[i] } }
$.ajax({ success:function (data) { handle(_adapter(data)) } })
function _adapter(data) { return JSON.stringify(data) }
|