---
title: "单例模式的标准写法、注意事项、作用及测试"
author: "Trinea"
date: "2013-09-09T20:57:30Z"
tags: []
categories: ["移动开发"]
slug: "untitled"
draft: false
lastmod: "2013-09-09T20:57:30Z"
id: 1939816
url: "https://trinea.iteye.com/blog/1939816"
---

最新最准确内容建议直接访问原文：[单例模式](http://www.trinea.cn/java/singleton/ "单例模式原文")

 

主要介绍**单例模式的标准写法、注意事项、作用、测试**，以Java语言为例，下面代码是目前见过最好的写法：

```
public class Singleton {

    private static volatile Singleton instance = null;

    // private constructor suppresses
    private Singleton(){
    }

    public static Singleton getInstance() {
        // if already inited, no need to get lock everytime
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }

        return instance;
    }
}
```

**1、需要注意的点**

其中需要注意的点主要有三点  
(1) 私有化构造函数  
(2) 定义静态的Singleton instance对象和getInstance()方法  
(3) getInstance()方法中需要使用同步锁synchronized (Singleton.class)防止多线程同时进入造成instance被多次实例化  
可以看到上面在synchronized (Singleton.class)外又添加了一层if，这是为了在instance已经实例化后下次进入不必执行synchronized (Singleton.class)获取对象锁，从而提高性能。

Ps: 也有实现使用的是private static Object    obj      = new Object();加上synchronized(obj)，实际没有必要多创建一个对象。[synchronized(X.class)](http://stackoverflow.com/questions/2056243/java-synchronized-block-for-class "different between synchronized(MyClass.class) and synchronized(this)") is used to make sure that there is exactly one Thread in the block.

 

**2、单例的作用**  
单例主要有两个作用  
(1) 保持程序运行过程中该类始终只存在一个示例  
(2) 对于new性能消耗较大的类，只实例化一次可以提高性能

 

**3、单例模式测试**

单例模式可以使用多线程并发进行测试，代码如下：

```
public static void main(String[] args) {
    final CountDownLatch latch = new CountDownLatch(1);
    int threadCount = 1000;

    for (int i = 0; i &lt; threadCount; i++) {
        new Thread() {

            @Override
            public void run() {
                try {
                    // all thread to wait
                    latch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                // test get instance
                System.out.println(Singleton.getInstance().hashCode());
            }
        }.start();
    }

    // release lock, let all thread excute Singleton.getInstance() at the same time
    latch.countDown();
}
```

其中CountDownLatch latch为闭锁，所有线程中都用latch.await();等待锁释放，待所有线程初始化完成使用latch.countDown();释放锁，从而达到线程并发执行Singleton.getInstance()的效果

 

**你可能还感兴趣：**

[Android公共库(缓存 下拉ListView 下载管理Pro 静默安装 root运行 Java公共类)](http://www.trinea.cn/?p=778)

[Android ImageCache图片缓存](http://www.trinea.cn/android/android-imagecache%e5%9b%be%e7%89%87%e7%bc%93%e5%ad%98%ef%bc%8c%e4%bd%bf%e7%94%a8%e7%ae%80%e5%8d%95%ef%bc%8c%e6%94%af%e6%8c%81%e9%a2%84%e5%8f%96%ef%bc%8c%e6%94%af%e6%8c%81%e5%a4%9a%e7%a7%8d%e7%bc%93/ "Android ImageCache图片缓存，使用简单，支持预取，支持多种缓存算法，支持不同网络类型，扩展性强")

[Android性能优化专题](http://www.trinea.cn/android/performance/ "性能优化之性能问题及性能调优方式")