js设计模式 -- 单例

// var Single = function(name) {
// 	this.name = name;
// 	this.instance = null;
// };
// 静态方法
// Single.getInstance = function(name) {
// 	if (!this.instance) {
// 		this.instance = new Single(name);
// 	}
// 	return this.instance;
// };

var CreateSingle = (function() {
	//这是个静态变量
	var instance;
	var CreateSingle = function(content) {
		if (instance) {
			instance.show(content);
			return instance;
		}
		//初次实例化
		this.content = content;
		this.init();
		//将单例对象指向this
		instance = this;
		return instance;
	};
	//单例对象实例化方法
	CreateSingle.prototype.init = function() {
		console.log('init');
	};
	//单例功能性方法
	CreateSingle.prototype.show = function(content) {
		console.log(content);
	};
	return CreateSingle;
})();

原文地址:https://www.cnblogs.com/smss/p/7357931.html