---
title: "创建型模式--单例模式(Singleton)"
author: "zhoumin007"
date: "2007-06-17T22:17:00Z"
tags: ["Access", "出版", "多线程", "数据结构"]
slug: "singleton"
draft: false
lastmod: "2007-06-17T22:17:00Z"
id: 96534
url: "https://zhoumin007.iteye.com/blog/96534"
---

**Singleton:**Ensure a class only has one instance, and provide a global point of access to it.

一个类只能有一个实例的创建模式。

**一：引入**

 在某些情况下一个类只能有一个实例，如果多于一个实例就会导致逻辑错误。

- 非共享资源：如打印机，系统属性文件
- 其他：如数据库主键生成器，只能有一个地方分配，否则会出现重复主键

<!--THE END-->

1. EagerSingleton(饿汉式单例)：

![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedBlock.gif)/\** \*//\**  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif) * 饿汉式单例  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockEnd.gif) \*/  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedBlock.gif)public class EagerSingleton ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    //类加载时实例化  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    private  static final EagerSingleton instance=new EagerSingleton();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    //构造函数设为私有，不能以new的方式生成新的实例  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    private EagerSingleton()  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)    ...{          
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)    }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    //提供给客户的得到唯一实例的方法  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    public static EagerSingleton getInstance()  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)    ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)         return instance;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)    }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockEnd.gif)}

 

 

![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedBlock.gif)public class Client ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)      public static void main(String args\[])  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)      ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)          EagerSingleton s1 = EagerSingleton.getInstance();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)          EagerSingleton s2 = EagerSingleton.getInstance();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        if( s1 == s2 )  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)          System.out.println( "s1 == s2" );  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)      }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockEnd.gif)}

问题：

- 类在加载时就将自己实例化，对于象资源控制器之类的类初始化可能耗费很多时间。还可能会导致出现多线程首次同时引用子类的几率变得比较大。
- 构造函数为私有,不能被继承。

<!--THE END-->

1. LazySingleton(懒汉式单例)--延迟加载(访问时加载)

![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedBlock.gif)/\** \*//\**  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif) * 懒汉式单例  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockEnd.gif) \*/  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedBlock.gif)public class LazySingleton ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    //类加载时为null，不实例化  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    private  static  LazySingleton instance=null;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    //构造函数设为私有，不能以new的方式生成新的实例  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    private LazySingleton()  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)    ...{          
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)    }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    //提供给客户的得到唯一实例的方法  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    public static LazySingleton getInstance()  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)    ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        //如果没有创建实例就创建，否则就用以前创建了的那个。  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        if (instance==null) instance=new LazySingleton();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)         return instance;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)    }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockEnd.gif)}

- 第一次访问时实例化，资源利用效率比饿汉式要好，但第一次访问时反应时间不如饿汉式。
- 因为构造函数私有，也不能被继承。

上例没有考虑到多线程环境,如果第一个线程执行到 if(instance==null)且还没有执行instance=new LazySingleton()时，另一个线程也执行到 if(instance==null)这时条件也为true，所以也会执行new LazySingleton()导致多实例。

 

![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)//整个方法都加锁,防止多线程环境下的问题  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)    synchronized public static LazySingleton getInstance()  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedBlock.gif)    ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        //如果没有创建实例就创建，否则就用以前创建了的那个。  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        if (instance==null) instance=new LazySingleton();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)         return instance;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockEnd.gif)    }

 

![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedBlock.gif)/\** \*//\**  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif) * 懒汉式单例,多线程环境  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockEnd.gif) \*/  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedBlock.gif)public class LazySingleton ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    // 类加载时为null，不实例化.  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    // volatile ensures that multiple threads handle the instance variable  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    // correctly  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    // when it is being initialized to the Singleton instance.  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    private volatile static LazySingleton instance = null;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    // 构造函数设为私有，不能以new的方式生成新的实例  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)    private LazySingleton() ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)    }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    // 两阶段加锁,防止多线程环境下的问题，效率比整个方法加锁高。  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)    public static LazySingleton getInstance() ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        // 如果没有创建实例就创建，否则就用以前创建了的那个。  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)        if (instance == null) ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)            synchronized (LazySingleton.class) ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)                if (instance == null) ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)                    instance = new LazySingleton();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)                }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)            }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)        }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        return instance;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)    }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockEnd.gif)}

 

**二：结构**

     **![](http://p.blog.csdn.net/images/p_blog_csdn_net/zhoumin008/Singleton.gif)**

**三：实际应用**

1. java.lang.Runtime

![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedBlock.gif)public class Runtime ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    private static Runtime currentRuntime = new Runtime();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)    /\** \*//\**  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)     * Returns the runtime object associated with the current Java application.  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)     * Most of the methods of class &lt;code&gt;Runtime&lt;/code&gt; are instance   
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)     * methods and must be invoked with respect to the current runtime object.   
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)     *   
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)     * @return  the &lt;code&gt;Runtime&lt;/code&gt; object associated with the current  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)     *          Java application.  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)     \*/  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)    public static Runtime getRuntime() ...{   
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    return currentRuntime;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)    }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)    /\** \*//\** Don't let anyone else instantiate this class \*/  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)    private Runtime() ...{}  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockEnd.gif)}

 

 

**四：适用情形**

Use the Singleton pattern when

- []()
- [there must be exactly one instance of a class, and it must be accessible to clients from a well-known access point.]()[]()
  
   
  
  []()[when the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying]()

[**参考文献：**  
1:阎宏，《Java与模式》，电子工业出版社  
2:Eric Freeman & Elisabeth Freeman，《Head First Design Pattern》，O'REILLY]()

[]()