1.单例模式特点
(1).单例类只能有一个实例。
(2).单例类必须自己创建自己的唯一实例。
(3).单例类必须给所有其他对象提供这一实例。
2.单例模式的几种实现方式
(1)饿汉式
public class Singleton { private static Singleton instance = new Singleton(); //直接初始化一个实例对象 private Singleton(){ //private类型的构造函数,保证其他类对象不能直接new一个该对象的实例 } public static Singleton getInstance(){ //该类唯一的一个public方法 return instance; } }
上述代码中的一个缺点是该类加载的时候就会直接new 一个静态对象出来,当系统中这样的类较多时,会使得启动速度变慢 。现在流行的设计都是讲“延迟加载”,我们可以在第一次使用的时候才初始化第一个该类对象。所以这种适合在小系统。
(2)懒汉式(线程安全)
public class Singleton { private static Singleton instance = null; private Singleton (){ } public static synchronized Singleton getInstance(){ //对获取实例的方法进行同步 if (instance == null) instance = new Singleton(); return instance; } }
将instance方法加上synchronized进行限定,确实可以解决线程安全问题,但会造成多线程调用该方法时串行执行,效率低下,如何改进呢?以下代码既可以保证线程安全又可以提高多线程并发的效率。
(3)多线程安全单例(双重同步锁)
public class Singleton { private static Singleton instance = null; private Singleton (){ } public static Singleton getInstance(){ //对获取实例的方法进行同步 if (instance != null){
return instance;
} synchronized(Singleton.class){ if (instance == null) instance = new Singleton(); } return instance; } }
或者这么写:
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; } }