创建型模式之单例模式
模式描述
单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。
注意:
- 1、单例类只能有一个实例。
- 2、单例类必须自己创建自己的唯一实例。
- 3、单例类必须给所有其他对象提供这一实例。
1、优点
- 1、在内存里只有一个实例,减少了内存的开销,尤其是频繁的创建和销毁实例(比如管理学院首页页面缓存)。
- 2、避免对资源的多重占用(比如写文件操作)。
2、缺点
- 没有接口,不能继承,与单一职责原则冲突,一个类应该只关心内部逻辑,而不关心外面怎么样来实例化。
3、UML图
我们将创建一个 SingleObject 类。SingleObject 类有它的私有构造函数和本身的一个静态实例。
SingleObject 类提供了一个静态方法,供外界获取它的静态实例。SingletonPatternDemo,我们的演示类使用 SingleObject 类来获取 SingleObject 对象。
模式实现
1、懒汉式,线程不安全
- 是否 Lazy 初始化:是
- 是否多线程安全:否
-
描述:这种方式是最基本的实现方式,这种实现最大的问题就是不支持多线程。因为没有加锁 synchronized,所以严格意义上它并不算单例模式。
这种方式 lazy loading 很明显,不要求线程安全,在多线程不能正常工作。
- 实例代码:
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
2、懒汉式,线程安全
- 是否 Lazy 初始化:是
- 是否多线程安全:是
- 描述:这种方式具备很好的 lazy loading,能够在多线程中很好的工作,但是,效率很低,99% 情况下不需要同步。
- 优点:第一次调用才初始化,避免内存浪费。
- 缺点:必须加锁 synchronized 才能保证单例,但加锁会影响效率。
-
getInstance() 的性能对应用程序不是很关键(该方法使用不太频繁)。
- 实例代码:
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
3、饿汉式
- 是否 Lazy 初始化:否
- 是否多线程安全:是
- 描述:这种方式比较常用,但容易产生垃圾对象。
- 优点:没有加锁,执行效率会提高。
- 缺点:类加载时就初始化,浪费内存。
-
它基于 classloder 机制避免了多线程的同步问题,不过,instance 在类装载时就实例化,虽然导致类装载的原因有很多种,在单例模式中大多数都是调用 getInstance 方法, 但是也不能确定有其他的方式(或者其他的静态方法)导致类装载,这时候初始化 instance 显然没有达到 lazy loading 的效果。
- 实例代码:
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton (){}
public static Singleton getInstance() {
return instance;
}
}
4、双重校验锁
- JDK 版本:JDK1.5 起
- 是否 Lazy 初始化:是
- 是否多线程安全:是
- 描述:这种方式采用双锁机制,安全且在多线程情况下能保持高性能。
-
getInstance() 的性能对应用程序很关键。
- 实例代码:
public class Singleton {
private volatile static Singleton singleton;
private Singleton (){}
public static Singleton getSingleton() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
5、静态内部类
- 是否 Lazy 初始化:是
- 是否多线程安全:是
- 描述:这种方式能达到双检锁方式一样的功效,但实现更简单。对静态域使用延迟初始化,应使用这种方式而不是双检锁方式。这种方式只适用于静态域的情况,双检锁方式可在实例域需要延迟初始化时使用。
-
这种方式同样利用了 classloder 机制来保证初始化 instance 时只有一个线程,它跟第 3 种方式不同的是:第 3 种方式只要 Singleton 类被装载了,那么 instance 就会被实例化(没有达到 lazy loading 效果),而这种方式是 Singleton 类被装载了,instance 不一定被初始化。因为 SingletonHolder 类没有被主动使用,只有显示通过调用 getInstance 方法时,才会显示装载 SingletonHolder 类,从而实例化 instance。想象一下,如果实例化 instance 很消耗资源,所以想让它延迟加载,另外一方面,又不希望在 Singleton 类加载时就实例化,因为不能确保 Singleton 类还可能在其他的地方被主动使用从而被加载,那么这个时候实例化 instance 显然是不合适的。这个时候,这种方式相比第 3 种方式就显得很合理。
- 实例代码:
public class Singleton {
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton (){}
public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
6、枚举
- JDK 版本:JDK1.5 起
- 是否 Lazy 初始化:否
- 是否多线程安全:是
- 描述:这种实现方式还没有被广泛采用,但这是实现单例模式的最佳方法。它更简洁,自动支持序列化机制,绝对防止多次实例化。
- 这种方式是 Effective Java 作者 Josh Bloch 提倡的方式,它不仅能避免多线程同步问题,而且还自动支持序列化机制,防止反序列化重新创建新的对象,绝对防止多次实例化。不过,由于 JDK1.5 之后才加入 enum 特性,用这种方式写不免让人感觉生疏,在实际工作中,也很少用。
-
不能通过 reflection attack 来调用私有构造方法。
- 实例代码:
public enum Singleton {
INSTANCE;
public void whateverMethod() {
}
}
漏洞和解决方案
1、反射漏洞和解决方案
- 问题实例代码:
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
Client类调用如下:
package singleton;
import java.lang.reflect.Constructor;
public class Client1 {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Singleton s1= Singleton.getInstance();
System.out.println(s1);
Class<Singleton> clazz = (Class<Singleton>) Class.forName("singleton.Singleton");
Constructor<Singleton> c = clazz.getDeclaredConstructor(null);
c.setAccessible(true);
Singleton s2 = c.newInstance();
System.out.println(s2);
}
}
后台输出如下:
singleton.Singleton2@15db9742
singleton.Singleton2@6d06d69c
-
: 问题描述:通过反射获得了多个实例对象。
-
解决方案:在单例类的构造方法中进行判断。
修改后代码用如下:
package singleton;
import java.io.ObjectStreamException;
import java.io.Serializable;
/**
* 懒汉式
* @author zhong
*
*/
public class Singleton2 {
private static Singleton2 singleton=null;
private Singleton2(){
if(null != singleton)
{
throw new RuntimeException();
}
}
public static synchronized Singleton2 getInstance()
{
if(null == singleton){
singleton = new Singleton2();
}
return singleton;
}
}
2、反序列化漏洞和解决方案
- 问题实例代码:
public class Singleton implements Serializable {
private static final long serialVersionUID = 8076919228683317537L;
private static Singleton instance;
private Singleton (){}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
Client类调用如下:
package singleton;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Client {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Singleton2 s1= Singleton2.getInstance();
System.out.println(s1);
FileOutputStream fos = new FileOutputStream("d:/a.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(s1);
oos.close();
fos.close();
FileInputStream fis = new FileInputStream("d:/a.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Singleton2 s2 = (Singleton2)ois.readObject();
ois.close();
fis.close();
System.out.println(s2);
}
}
后台输出如下:
singleton.Singleton2@15db9742
singleton.Singleton2@6d06d69c
-
: 问题描述:通过反序列化获得了多个实例对象。
-
解决方案:在单例类的readResolve方法中指定返回对象。
修改后代码用如下:
package singleton;
import java.io.ObjectStreamException;
import java.io.Serializable;
/**
* 懒汉式
* @author zhong
*
*/
public class Singleton2 implements Serializable {
private static final long serialVersionUID = 8076919228683317537L;
private static Singleton2 singleton=null;
private Singleton2(){
if(null != singleton)
{
throw new RuntimeException();
}
}
public static synchronized Singleton2 getInstance()
{
if(null == singleton){
singleton = new Singleton2();
}
return singleton;
}
/**
* 在反序列化时,返回指定的对象,不需要创建新的对象
* @return
* @throws ObjectStreamException
*/
private Object readResolve() throws ObjectStreamException{
return singleton;
}
}
性能测试
- 描述:CountDownLatch,同步辅助类,在完成一组正在其他线程中执行的操作之前,它谲诈一个或多个线程一直等待。
- countDown() 当前线程调用此方法,则计数减一,建议放在finally里执行
- await(),调用此方法会一直阻塞当前线程,直到计时器的值为0
- 测试代码:
package singleton;
import java.util.concurrent.CountDownLatch;
public class Test {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
long starttime = System.currentTimeMillis();
int threadNum = 10;
final CountDownLatch countDownLatch = new CountDownLatch(threadNum);
for(int i=0;i<10;i++){
new Thread( new Runnable(){
@Override
public void run() {
for(int i=0;i<1000000;i++){
Object o = Singleton6.INSTANCE;
}
countDownLatch.countDown();
}
}).start();
}
//main线程阻塞,直到计数器变为0,才会继续往下执行
countDownLatch.await();
long endtime = System.currentTimeMillis();
System.out.println("总耗时="+(endtime-starttime));
}
}
总结
- 饿汉式:线程安全、调用效率高、不能延时加载
- 懒汉式:线程安全、调用效率不高、可以延时加载
- 双重检测锁:由于JVM底层内部的模型原因,偶尔会出问题,不建议使用
- 静态内部类:线程安全、调用效率高、可以延时加载
- 枚举式:线程安全、调用效率高、不能延时加载,并且可以天然的防止反射和反序列化漏洞
- 如何选用:
–单例对象占用资源少 不需要延时加载:枚举式 好于 饿汉式
– 单例对象占用资源多 需要延时加载:静态内部类式好于懒汉式