单例模式

定义 确保一个类只有一个实例,并提供一个全局访问点。
延迟实例化

public class Singleton {
	private static Singleton instance;

	private Singleton() { //构造函数私有化;
	};

	public static Singleton getInstatnce() { //全局访问点;
		if (instance == null) {
			instance = new Singleton();
		}
		return instance;
	}
}

注意对于多线程可能存在同时创建出多个实例出来,
延迟实例化的改进


public class Singleton {
	private static Singleton instance;

	private Singleton() { //构造函数私有化;
	};


//加入synchronized进行同步,但是性能会下降;
	public static synchronized Singleton getInstatnce() { //全局访问点;
		if (instance == null) {
			instance = new Singleton();
		}
		return instance;
	}
}

不延迟

//JVM加载这个类的时候就创建实例;
public class Singleton {
	private static Singleton instance =  new Singleton();

	private Singleton() { //构造函数私有化;
	};

	public static synchronized Singleton getInstatnce() { //全局访问点;
	
		return instance;
	}
}

双重检查加锁


public class Singleton {
	private volatile static Singleton instance ;

	private Singleton() { //构造函数私有化;
	};

	public static  Singleton getInstatnce() { //全局访问点;
	
		if(instance==null) {
			synchronized(Singleton.class){ //实例化的时候才加锁;
				instance = new Singleton();
			}
		}
		return instance;
	}
}

posted @ 2018-08-09 16:42  LynnMin  阅读(120)  评论(0编辑  收藏  举报