---
title: "7种单例模式"
author: "popwang"
date: "2011-06-30T15:36:00Z"
tags: []
categories: ["编程语言"]
slug: "7"
draft: false
lastmod: "2011-06-30T15:36:00Z"
id: 1110754
url: "https://popwang.iteye.com/blog/1110754"
---

**第一种（懒汉，线程不安全）：**

 

Java代码  [![收藏代码](http://cantellow.iteye.com/images/icon_star.png)]()

1. public   class  Singleton {
2. private   static  Singleton instance;
3. public   static  Singleton getInstance() {
4. if  (instance ==  null ) {
5. instance = new  Singleton();
6. }
7. return  instance;
8. }
9. }

 这种写法lazy loading很明显，但是致命的是在多线程不能正常工作。

**第二种（懒汉，线程安全）：**

 

Java代码  [![收藏代码](http://cantellow.iteye.com/images/icon_star.png)]()

1. public   class  Singleton {
2. private   static  Singleton instance;
3. public   static   synchronized  Singleton getInstance() {
4. if  (instance ==  null ) {
5. instance = new  Singleton();
6. }
7. return  instance;
8. }
9. }

 这种写法能够在多线程中很好的工作，而且看起来它也具备很好的lazy loading，但是，遗憾的是，效率很低，99%情况下不需要同步。

**第三种（饿汉）：**

 

Java代码  [![收藏代码](http://cantellow.iteye.com/images/icon_star.png)]()

1. public   class  Singleton {
2. private   static  Singleton instance =  new  Singleton();
3. public   static  Singleton getInstance() {
4. return  instance;
5. }
6. }

 这种方式基于 classloder 机制避免了多线程的同步问题，不过， instance 在类装载时就实例化，虽然导致类装载的原因有很多种，在单例模式中大多数都是调用 getInstance 方法，   但是也不能确定有其他的方式（或者其他的静态方法）导致类装载，这时候初始化 instance 显然没有达到 lazy loading 的效果。

**第四种（饿 汉，变种）：**

 

Java代码  [![收藏代码](http://cantellow.iteye.com/images/icon_star.png)]()

1. public   class  Singleton {
2. private  Singleton instance =  null ;
3. static  {
4. instance = new  Singleton();
5. }
6. public   static  Singleton getInstance() {
7. return   this .instance;
8. }
9. }

 

 表面上看起来差别挺大，其实更第三种方式差不多，都是在类初始化即实例化instance。

**第五种（静态内部类）：**

 

Java代码  [![收藏代码](http://cantellow.iteye.com/images/icon_star.png)]()

1. public   class  Singleton {
2. private   static   class  SingletonHolder {
3. private   static   final  Singleton INSTANCE =  new  Singleton();
4. }
5. public   static   final  Singleton getInstance() {
6. return  SingletonHolder.INSTANCE;
7. }
8. }

 

这种方式同样利用了 classloder 的机制来保证初始化 instance 时只有一个线程，它跟第三种和第四种方式不同的是（很细微的差别）：第三种和第四种方式是只要 Singleton 类被装载了，那么 instance 就会被实例化（没有达到 lazy loading 效果），而这种方式是 Singleton 类被装载了， instance 不一定被初始化。因为 SingletonHolder 类没有被主动使用，只有显示通过调用 getInstance 方法时，才会显示装载 SingletonHolder 类，从而实例化 instance 。想象一下，如果实例化 instance 很消耗资源，我想让他延迟加载，另外一方面，我不希望在 Singleton 类加载时就实例化，因为我不能确保 Singleton 类还可能在其他的地方被主动使用从而被加载，那么这个时候实例化 instance 显然是不合适的。这个时候，这种方式相比第三和第四种方式就显得很合理。

**第六种（枚举）：**

 

Java代码  [![收藏代码](http://cantellow.iteye.com/images/icon_star.png)]()

1. public   enum  Singleton {
2. INSTANCE;
3. public   void  whateverMethod() {
4. }
5. }

 

 这种方式是Effective Java作者Josh Bloch 提倡的方式，它不仅能避免多线程同步问题，而且还能防止反序列化重新创建新的对象，可谓是很坚强的壁垒啊，不过，个人认为由于1.5中才加入enum特 性，用这种方式写不免让人感觉生疏，在实际工作中，我也很少看见有人这么写过。

**第七种（双重校验锁）：**

 

Java代码  [![收藏代码](http://cantellow.iteye.com/images/icon_star.png)]()

01. public   class  Singleton {
02. private   volatile   static  Singleton singleton;
03. public   static  Singleton getSingleton() {
04. if  (singleton ==  null ) {
05. synchronized  (Singleton. class ) {
06. if  (singleton ==  null ) {
07. singleton = new  Singleton();
08. }
09. }
10. }
11. return  singleton;
12. }
13. }

 

 这个是第二种方式的升级版，俗称双重检查锁定，详细介绍请查看：[http://www.ibm.com/developerworks/cn/java/j-dcl.html](http://www.ibm.com/developerworks/cn/java/j-dcl.html)

在JDK1.5之后，双重检查锁定才能够正常达到单例效果。

 

**总结**

有两个问题需要注意：

1.如果单例由不同的类装载器装入，那便有可能存在多个单例类的实例。假定不是远端存取，例如一些servlet 容器对每个servlet 使用完全不同的类装载器，这样的话如果有两个servlet 访问一个单例类，它们就都会有各自的实例。

2.如果Singleton 实现了java.io.Serializable 接口，那么这个类的实例就可能被序列化和复原。不管怎样，如果你序列化一个单例类的对象，接下来复原多个那个对象，那你就会有多个单例类的实例。

对第一个问题修复的办法是：

 

Java代码  [![收藏代码](http://cantellow.iteye.com/images/icon_star.png)]()

1. private   static  Class getClass(String classname)
2. throws  ClassNotFoundException {
3. ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
4. if (classLoader ==  null )
5. classLoader = Singleton.class .getClassLoader();
6. return  (classLoader.loadClass(classname));
7. }
8. }

 对第二个问题修复的办法是：

 

Java代码  [![收藏代码](http://cantellow.iteye.com/images/icon_star.png)]()

1. public   class  Singleton  implements  java.io.Serializable {
2. public   static  Singleton INSTANCE =  new  Singleton();
3. protected  Singleton() {
4. }
5. private  Object readResolve() {
6. return  INSTANCE;
7. }
8. }

 

对我来说，我比较喜欢第三种和第五种方式，简单易懂，而且在JVM层实现了线程安全（如果不是多个类加载器环境），一般的情况下，我会使用第三种方 式，只有在要明确实现lazy loading效果时才会使用第五种方式，另外，如果涉及到反序列化创建对象时我会试着使用枚举的方式来实现单例，不过，我一直会保证我的程序是线程安全 的，而且我永远不会使用第一种和第二种方式，如果有其他特殊的需求，我可能会使用第七种方式，毕竟，JDK1.5已经没有双重检查锁定的问题了。

========================================================================

 [superheizai](http://superheizai.iteye.com/) 同学总结的很到位：

 

不过一般来说，第一种不算单例，第四种和第三种就是一种，如果算的话，第五种也可以分开写了。所以说，一般单例都是五种写法。懒汉，恶汉，双重校验锁，枚举和静态内部类。

我很高兴有这样的读者，一起共勉。

鉴于很多人说我没有写私有构造方法，我这里声明一下，不是我忘了写，是我故意嫌麻烦省略掉了，我以为大家都懂得 ![](http://cantellow.iteye.com/images/smiles/icon_redface.gif)