单例模式算是一种很常用到的设计模式之一了,今天就来聊一聊在不同场景下如何去实现单例。
单例模式的概念就是:保证一个类只有一个实例,并提供一个访问它的全局访问点。
主要作用呢,就是保证在Java应用程序中,一个类Class只有一个实例存在。
单例模式一般分为 懒汉式 以及 饿汉式。
单例的几种写法:
1.懒汉式(立即加载方式)
public class Singleton {
private static Singleton instance = new Singleton();
public static Singleton getInstance() {
return instance;
}
}
这种写法比较简单,在类加载的时候就完成了实例化,避免了线程同步问题。
但是如果从始至终从未使用过这个实例,则会造成内存的浪费。
2.饿汉式(延迟加载方式)
public class Singleton {
private static Singleton uniqeInstance = null;
public static Singleton getInstance(){
if (uniqeInstance == null) {
uniqeInstance = new Singleton();
}
return uniqeInstance;
}
}
多线程下不可使用该方式,如果线程1执行完if (uniqeInstance == null)
,还没开始往下执行,线程2也通过了这个判断语句,这时便会产生多个实例。
单例模式在多线程操作时的方式:
3.方法上加synchronized(缺点:消耗过多资源)
public class Singleton {
public static Singleton instance = null;
public static synchronized Singleton getInstance() {
if (instance == null ) {
instance = new Singleton();
}
return instance ;
}
}
4.急切法 创建实例多次 (缺点:消耗内存)
public class Singleton {
public static Singleton instance = new Singleton();
public static Singleton getInstance() {
if (instance == null ) {
instance = new Singleton();
}
return instance;
}
}
5.双重检查加锁法(建议使用)
public class Singleton {
public volatile static Singleton instance = null;
public static Singleton getInstance() {
if (instance == null ) {
synchronized (Singleton.class) {
if (instance == null ) {
instance = new Singleton();
}
}
}
return instance;
}
}
注意:这里静态变量中的volatile关键字的作用主要有两个:
1).保证了不同线程对这个变量进行操作时的可见性;
2).禁止了指令重排序
也正是因为这两点,当多个线程操作时,不管到哪一步,只要读到instance的值已改变,则会直接从内存中读取,就不会存在创建多个实例的情况。
6.枚举(用的较少)
public enum SingletonEnum {
INSTANCE;
public void whateverMethod() {
}
}
借助JDK1.5中添加的枚举来实现单例模式。不仅能避免多线程同步问题,而且还能防止反序列化重新创建新的对象。