日期:2014-05-16  浏览次数:20340 次

Java, C#, JavaScript三种语言实现单例模式

无论任何一门语言,模式的思想都一样,不一样的就是语言的细节。

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 });