以下文字描述来源于菜鸟教程。
单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。
注意:
1、单例类只能有一个实例。
2、单例类必须自己创建自己的唯一实例。
3、单例类必须给所有其他对象提供这一实例。
介绍
- 意图:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
- 主要解决:一个全局使用的类频繁地创建与销毁。
- 何时使用:当您想控制实例数目,节省系统资源的时候。
- 如何解决:判断系统是否已经有这个单例,如果有则返回,如果没有则创建。
- 关键代码:构造函数是私有的。
一、饿汉式(静态常量 )
class Singleton {
// 构造器私有化
private Singleton() {
}
// 本类内部创建对象实例
private final static Singleton instance = new Singleton();
// 提供一个公有的静态方法,返回实例对象
public static Singleton getInstance() {
return instance;
}
}
分析:
- 优点:这种写法比较简单,就是在类装载的时候就完成实例化。避免了线程同步问题。
- 缺点:在类装载的时候就完成实例化,没有达到懒加载的效果。
- 这种方式基于 classloder 机制避免了多线程的同步问题,不过,instance在类装载时就实例化,在单例模式中大多数都是调用getInstance方法,但是导致类装载的原因有很多种,因此不能确定有其他的方式(或者其他的静态方法)导致类装载,这时候初始化instance就没有达到 Lazy Loading 的效果。
二、饿汉式(静态代码块)
class Singleton {
// 构造器私有化
private Singleton() {
}
// 本类内部创建对象实例
private static Singleton instance;
static { // 在静态代码块中,创建单例对象
instance = new Singleton();
}
// 提供一个公有的静态方法,返回实例对象
public static Singleton getInstance() {
return instance;
}
}
分析:
- 这种方式和上面的方式其实类似,只不过将类实例化的过程放在了静态代码块 中,也是在类装载的时候,就执行静态代码块中的代码,初始化类的实例。优 缺点和上面是一样的。
- 这种单例模式可用,但是可能造成内存浪费
三、懒汉式( 线程不安全)
class Singleton {
private static Singleton instance;
// 构造器私有化
private Singleton() {
}
// 提供一个静态的公有方法,当使用到该方法时,才去创建 instance
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
分析:
- 起到了Lazy Loading的效果,但是只能在单线程下使用。
- 如果在多线程下,一个线程进入了if (singleton == null)判断语句块,还未来得及往下执行,另一个线程也通过了这个判断语句,这时便会产生多个实例。所以 在多线程环境下不可使用这种方式。
- 在实际开发中,不要使用这种方式
四、饿汉式( 线程安全,同步方法)
class Singleton {
private static Singleton instance;
// 构造器私有化
private Singleton() {
}
// 提供一个静态的公有方法,加入同步处理的代码,解决线程安全问题
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
分析:
- 解决了线程不安全问题。
- 效率太低,每个线程在想获得类的实例时候,执行getInstance()方法都要进行同步。而这个方法只执行一次实例化代码就够了,后面的想获得该类的实例, 直接return就行。方法进行同步效率太低。
五、懒汉式( 线程不安全,同步代码块)
class Singleton {
private static volatile Singleton instance;
// 构造器私有化
private Singleton() {
}
// 提供一个静态的公有方法,线程不安全,Why ?
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
// 模仿多线程环节,加上这一句会出现什么问题?
// TimeUnit.SECONDS.sleep(3);
instance = new Singleton();
}
}
return instance;
}
}
分析:
- 这种方式,本意是想对第四种实现方式的改进,因为前面同步方法效率太低, 改为同步产生实例化的的代码块。
- 这种同步并不能起到线程同步的作用 。跟第3种实现方式遇到的情形一致,假如一个线程进入了if (singleton == null)判断语句块,还未来得及往下执行, 另一个线程也通过了这个判断语句,这时便会产生多个实例。
六 、双重检查(DCL 懒汉式)
class Singleton {
// 不是一个原子性操作
//private static Singleton instance;
//改进,Volatile 可以保持可见性,不能保证原子性,由于内存屏障,可以保证避免指令重排的现象产生!
private static volatile Singleton instance;
// 构造器私有化
private Singleton() {
}
// 提供一个静态的公有方法,加入双重检查代码,解决线程安全问题, 同时解决懒加载问题,同时保证了效率, 推荐使用
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
分析:
- Double-Check概念是多线程开发中常使用到的,如代码中所示,我们进行了两次if (singleton == null)检查,这样就可以保证线程安全了。
- 实例化代码只用执行一次,后面再次访问时,判断if (singleton == null), 直接return实例化对象,也避免的反复进行方法同步。
- 线程安全,延迟加载,效率较高。
- private static Singleton instance; 不是一个原子性操作
七、静态内部类
class Singleton {
private static volatile Singleton instance;
// 构造器私有化
private Singleton() {
}
// 写一个静态内部类,该类中有一个静态属性 Singleton
private static class SingletonInstance {
private static final Singleton INSTANCE = new Singleton();
}
// 提供一个静态的公有方法,直接返回SingletonInstance.INSTANCE
public static synchronized Singleton getInstance() {
return SingletonInstance.INSTANCE;
}
}
分析:
- 这种方式采用了类装载的机制来保证初始化实例时只有一个线程。
- 静态内部类方式在Singleton类被装载时并不会立即实例化,而是在需要实例化时,调用getInstance方法,才会装载SingletonInstance类,从而完成Singleton的实例化。
- 类的静态属性只会在第一次加载类的时候初始化,所以在这里,JVM帮助我们保证了线程的安全性,在类进行初始化时,别的线程是无法进入的。
- 避免了线程不安全,利用静态内部类特点实现延迟加载,效率高。
前面写的单例模式真的单例?
口说无凭,咱们以事实说话。。。
import java.lang.reflect.Constructor;
import org.junit.Test;
public class MyTest {
@Test
public void testSingleton() throws Exception {
Constructor<Singleton> constructor = Singleton.class.getDeclaredConstructor();
constructor.setAccessible(true);
// 若此时只使用反射获取单例模式,单例模式不可用
Singleton instance1 = constructor.newInstance();
Singleton instance2 = constructor.newInstance();
System.out.println(instance1); // com.webjuly.Singleton@3d82c5f3
System.out.println(instance2); // com.webjuly.Singleton@2b05039f
}
}
// 懒汉式(线程安全,同步方法)
class Singleton {
private static volatile Singleton instance;
// 构造器私有化
private Singleton() {
}
// 提供一个静态的公有方法,加入双重检查代码,解决线程安全问题, 同时解决懒加载问题
// 同时保证了效率, 推荐使用
public static synchronized Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
好家伙,说好的单例呢?
又被欺骗了。
别着急,所谓魔高一尺道高一丈。既然知道怎么破坏那咱们就有应对之法。
策略一
class Singleton {
private static volatile Singleton instance;
private static boolean flag = false;
// 构造器私有化
private Singleton() {
if (!flag) {
flag = true;
} else {
throw new RuntimeException("呸,臭不要脸!妄图破坏我研究了一个月的单例!");
}
}
// 提供一个静态的公有方法,加入双重检查代码,解决线程安全问题, 同时解决懒加载问题
// 同时保证了效率, 推荐使用
public static synchronized Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
这样真的安全了么?
不见得。。。
策略二
@Test
public void test() throws Exception {
Field flag = Singleton.class.getDeclaredField("flag");
flag.setAccessible(true);
Constructor<Singleton> constructor = Singleton.class.getDeclaredConstructor();
constructor.setAccessible(true);
Singleton instance1 = constructor.newInstance();
flag.set(instance1, false);
Singleton instance2 = constructor.newInstance();
flag.set(instance1, false);
System.out.println(instance1);
System.out.println(instance2);
}
哎呦! 情况有点不太对哦(⊙o⊙)?毫无疑问,又被打脸了,我要出大招了,请看下一种写法。。。。。。
八、终极大招之——枚举
enum Singleton {
INSTANCE; // 属性
public Singleton getInstance() {
return INSTANCE;
}
}
分析:
- 这借助JDK1.5中添加的枚举来实现单例模式。不仅能避免多线程同步问题,而且还能防止反序列化重新创建新的对象。
- 这种方式是Effective Java作者Josh Bloch 提倡的方式
枚举怎么就安全呢?请看。。。
@Test
public void test() throws Exception {
Constructor<EnumSingle> constructor = EnumSingle.class.getDeclaredConstructor();
constructor.setAccessible(true);
EnumSingle instance1 = constructor.newInstance();
EnumSingle instance2 = constructor.newInstance();
System.out.println(instance1);
System.out.println(instance2);
}
😄😄O(∩_∩)O,总算把丢了的场子找回来了!这下反射没用了吧,啦啦 啦啦啦。。。
十、单例模式在 JDK 中的应用
1 、java.lang.Runtime
public class Runtime {
// 典型的饿汉式(静态常量 )
private static Runtime currentRuntime = new Runtime();
/**
* Returns the runtime object associated with the current Java application.
* Most of the methods of class <code>Runtime</code> are instance
* methods and must be invoked with respect to the current runtime object.
*
* @return the <code>Runtime</code> object associated with the current
* Java application.
*/
public static Runtime getRuntime() {
return currentRuntime;
}
}
2、java.awt.Toolkit
public abstract class Toolkit {
private static Toolkit toolkit;
// 懒汉式(线程安全,同步方法)
public static synchronized Toolkit getDefaultToolkit() {
if (toolkit == null) {...}
return toolkit;
}
}
3、java.awt.GraphicsEnvironment
public abstract class GraphicsEnvironment {
private static GraphicsEnvironment localEnv;
/**
* This is an abstract class and cannot be instantiated directly.
* Instances must be obtained from a suitable factory or query method.
*/
protected GraphicsEnvironment() {
}
/**
* Returns the local <code>GraphicsEnvironment</code>.
* @return the local <code>GraphicsEnvironment</code>
*/
public static synchronized GraphicsEnvironment getLocalGraphicsEnvironment() {
if (localEnv == null) { // 懒汉式(线程安全,同步方法)
localEnv = createGE();
}
return localEnv;
}
}
嗯,最后发个言。。。
推荐使用下面这几种方式,根据自己需要选择其中之一即可
1、饿汉式(静态常量 )
2、饿汉式(静态代码块)
6、双重检查(DCL 懒汉式)
7、静态内部类
8、终极大招之——枚举
针对文章可能存在的一些不足之处,请大佬指出,经核实以后会尽快对文章进行修改,感谢您的支持!!!