JavaScript常用设计模式

单例模式:确保类只能被实例化一次。

var obj = {}
2、函数返回值
var func = function () {return {}}
var obj = func();
3、构造函数初始化
var obj = (function () {return {}})()

装饰者模式:装饰者用用于包装同接口的对象。

var obj = obj || {}
obj.set = function(){}
obj.get = function(){}
obj.……= function(){}

模块模式:该模式使用闭包封装私有状态和组织。

var module = (function(obj){})({});

观察者模式:它定义了一种一对多的关系,让多个观察者对象同时监听某一个主题对象。

function func() {}
func.prototype.set = function(opt){}
func.prototype.get = function(opt){}
var obj = new func();
obj.set({});
obj.get({});

构造函数模式:自定义自己的构造函数,然后在里面声明自定义类型对象的属性或方法。 

1、构造函数
function func(name,age){
	this.id = 0;
	//code……
}
func.prototype.pro = function(){}
2、构造函数强制实例化
function func(title) {
    if (!(this instanceof func)) {
        return new func(title);
    }
    this.title = title;
}
func.prototype.get = function () { return this.title; }
console.log(obj.get());

工厂模式:工厂模式就好比现实生活中的工厂可以产生大量相似的产品。

function func(opt){
	var obj = {
		id:0,
		title:''
	}
	return $.extend(obj,opt);
}
var f1 = func({id:1,title:'标题1'});
var f2 = func({id:2,title:'标题2'});

对象创建模式:对象中创建对象

模式1:命名空间(namespace)
var obj = obj || {};
obj.app = obj.app || {};
obj.app.ios = obj.app.ios || {};
obj.app.android = obj.app.android || {};
模式2:通过自执行函数创建对象
var obj;
(function () {
	obj = {}
})
模式3:链模式
var obj = {
	func1: function () {return this;},
	func2: function () {return this;},
	……: function () {return this;}
}
// 链方法调用
obj.func1().func2().……();
模式4:函数语法糖
函数语法糖是为一个对象快速添加方法(函数)的扩展,这个主要是利用prototype的特性
if (typeof Function.prototype.method !== "function") {
    Function.prototype.method = function (name, implementation) {
        this.prototype[name] = implementation;
        return this;
    };
}
var func = function (name) {
    this.name = name;
}.method('set', function (name) {
    this.name = name;           
}).method('get', function () {
    return this.name;
});
var a = new func('a');
a.set('b');
console.log(a.get());

沙盒模式

原文地址:https://www.cnblogs.com/sntetwt/p/8726324.html