Java设计模式之单例模式-学习笔记二

Java设计模式之单例模式-学习笔记2

两种方式实现Java设计模式之单例模式,单例在程序应用中是非常常见的一种设计模式之一,其思想和代码实现都非常的简单,单例单例顾名思义在程序运行的过程中只会产生一个实例,接下来看看代码的实现:

 

Coding:

public class Singleton {

	private static Singleton instance = null;

	private Singleton() {
	}

	// 线程安全的单例模式 效率高
	public static Singleton getInstance() {
		if (instance == null) {
			synchronized (Singleton.class) {
				if (instance == null) {
					instance = new Singleton();
				}
			}
		}
		return instance;
	}

	// 线程安全的单例模式 效率低
	public synchronized static Singleton getInstance2() {
		if (instance == null) {
			instance = new Singleton();
		}
		return instance;
	}
}



public class Singleton2 {

	private static Singleton2 instance = new Singleton2();

	private Singleton2() {
	}

	// 线程安全 类加载的时候就new一个实例放置在了静态块内
	public static Singleton2 getInstance() {
		return instance;
	}

}