单例模式
1. 引言
单例模式是最常见,也是最常使用的设计模式之一。我们在使用单例模式的时候,应该确保单例的类只能有创建一个对象
。
在开发过程中,很多时候一个类我们希望它只创建一个对象,比如:线程池、缓存、网络请求等。当这类对象有多个实例时,程序就可能会出现异常,比如得到的结果不一致等等。这种时候我们就会使用单例模式。
单例模式主要有两个优点:
-
提供了对唯一实例的受控访问。
-
节约系统资源,对于一些需要频繁创建和销毁的对象,单例模式可以提高系统的性能。
接下来将介绍几种常见的实现单例的方式。
2. 饿汉式(静态常量) 【可以用】
优点:写法比较简单,就是在类装载
的时候就完成实例化。避免了线程同步问题。
缺点:在类装载的时候就完成实例化,没有达到Lazy Loading(懒加载)的效果。如果从始至终从未使用过这个实例,则会造成内存的浪费。
public class Singleton {
private final static Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance(){
return INSTANCE;
}
}
3. 懒汉式(线程不安全)【不建议用】
- 起到了Lazy Loading(懒加载)的效果,
- 只能在单线程下使用。如果在多线程下,一个线程进入了if (singleton == null)判断语句块,还未来得及往下执行,另一个线程也通过了这个判断语句,这时便会产生多个实例。所以在多线程环境下不可使用这种方式。
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
4. 懒汉式(线程安全,同步方法)【不建议用】
- 对getInstance()方法进行了线程同步。
- 缺点:效率太低了,每个线程在想获得类的实例时候,执行getInstance()方法都要进行同步。每次需要判断instance == null也同步了
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
5. 懒汉式 同步代码快+双重检查【建议使用】
在singleton为null的时候,才需要加锁,因为防止多线程重复创建对象
当singleton不为null的时候,就不需要锁了,直接判断返回就可以了
优点:线程安全;延迟加载;效率较高。
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
6. 静态内部类【建议使用】
- 外部类加载时,并不会加载内部类,也就不会执行
new Singleton()
,这属于懒加载。只有第一次调用getInstance()
方法时才会加载 Singleton类。
public class Singleton {
private Singleton() {}
private static class SingletonInstance {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
Comments NOTHING