無論任何一門語言,模式的思想都一樣,不一樣的就是語言的細節。
Java版:
public class Singleton {
private volatile static Singleton instance;
private Singleton(){};
public static Singleton getInstance()
{
if(instance == null){
synchronized (Singleton.class) {
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
C#版:public class Singleton
{
protected Singleton() { }
private static volatile Singleton instance = null;
/// Lazy方式創建唯一實例的過程
public static Singleton Instance()
{
if (instance == null) // 外層if
lock (typeof(Singleton)) // 多線程中共享資源同步
if (instance == null) // 內層if
instance = new Singleton();
return instance;
}
}
JS版:var singletonTest=(function(){
function single(args){
var args=args || [];
this.name='singletontest';
this.x=args.x || 6;
this.y=args.y || 7;
};
var instance;
var _static={
name:'singletontest',
getInstance:function(args){
if( instance === undefined)
{
instance = new single(args);
}
return instance;
}
};
return -static;
})();
//調用 var singletonTest = SingletonTester.getInstance({ pointX: 5 });