一.单件模式通常实现
二.单件模式多线程实现
一.单件模式通常实现java
public class Singleton { private static Singleton uniqueInstance; private Singleton() {} public static Singleton getInstance() { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; } }
二.单件模式多线程实现多线程
public class Singleton { private static Singleton uniqueInstance; private Singleton() {} public synchronized static Singleton getInstance() { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; } }
问题:性能下降性能
A. 如何getInstance()的性能对应用程序不是关键,就什么都不要作.同步可能使应用程序的执行效率下降100倍,但若是此方法不是被频繁的调用,则不用修改.由于同步的getInstance()方法既简单又有效.线程
B.使用"急切"建立实例,而不用延迟化的实例的方法code
public class Singleton { private static Singleton uniqueInstance = new Singleton(); public synchronized Singleton getInstance() { return uniqueInstance; } }
C.使用"双重检查加锁",尽可能减小使用同步:若是性能是你关心的,此方法可大大减小时间消耗get
public class Singleton { private static volatile Singleton uniqueInstance; public static Singleton getInstance() { if (uniqueInstance == null) { synchronized (Singleton.class) { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } } } return uniqueInstance; } }