参考链接:
1. Singleton 模式
JS:版本
// ///Singleton 模式 function Singleton() { if (Singleton.caller != Singleton.getInstance) { throw new Error( " Can't new Singleton instance! " ); } // ///禁止用户直接实例化Singleton类 this .prop1 = " Hello " ; this .method1 = function (x, y) { return x + y; } } Singleton.__instance__ = null ; Singleton.getInstance = function () { if ( this .__instance__ == null ) { this .__instance__ = new Singleton(); } return this .__instance__; } var obj = Singleton.getInstance(); // /返回Singleton类的唯一实例
C#
代码
public class singleton { private static singleton uniqueInstance; /// /利用一个静态变量来记录Singleton类的唯一实例 private singleton() { } /// /把构造器设为私有的,只有自Singleton类内才可以调用构造器 public static singleton getInstance() /// /用 getInstance()方法实例化对象,并返回这个实例 { if (uniqueInstance == null ) { uniqueInstance = new singleton(); } return uniqueInstance; } }