---
title: "JAVA设计模式：单例（Singleton）"
author: "fancy888"
date: "2012-07-12T16:51:48Z"
tags: []
categories: ["编程语言"]
slug: "java-singleton"
draft: false
lastmod: "2012-07-13T12:58:32Z"
id: 1586906
url: "https://fancy888.iteye.com/blog/1586906"
---

单例（Singleton）设计模式保证每个类只有一个实例，并为这个实例提供一个全局的访问点。

      与工具类中的静态成员不同，单例类一般用来保存应用程序的状态数据，这些数据在应用程序的各个部分都可能被访问或修改。

      单例模式的几种实现方式。

```
public class Singleton{
    private static Singleton instance = new Singleton();

    public static Singleton getInstance() {
        return instance;
    }

   /** Don't let anyone else instantiate this class */
   private Singleton() {
   }
}
```

 

      这种方式实现简单，并且保证实例的唯一性，缺点是必须先加载后使用，而且不管单例类是否真正使用到，实例总是会先被加载，这看起来相当的不妥，因而有了懒加载（Lazy Initialization）的模式。

 

```
public class Singleton {
    private static Singleton instance = null;

    private Singleton() {

    }

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}
```

 

      这种方式可以实现懒加载，但当多个线程同时进入getInstance方法时，可能会产生多份实例，这显然违背单例模式的初衷。为了避免这种情况，考虑加上同步（synchronized）机制。

 

```
public class Singleton {
    private static Singleton instance = null;

    private Singleton(){
    }

    synchronized static public Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}
```

 

     这种方式可以在懒加载的同时保证只有一份实例，但对整个getInstance方法作同步处理会带来线程同步上的性能消耗。

 

```
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;
    }
}
```

 

     上面的方式就是所谓的Double-check Locking即双重检查和锁定模式，目前看来很完美。

 

      [阅读全文](http://www.coolfancy.com/log/19.html)

      [更多JAVA设计模式](http://www.coolfancy.com/log/37.html)

      更多精彩原创文章请关注笔者的原创博客：[http://www.coolfancy.com](http://www.coolfancy.com)