---
title: "设计模式快速参考－单例模式"
author: "gurudk"
date: "2008-12-06T06:46:21Z"
tags: ["多线程", "设计模式"]
slug: "untitled"
draft: false
lastmod: "2009-02-01T21:10:29Z"
id: 288029
url: "https://gurudk.iteye.com/blog/288029"
---

```
class Singleton{

   private Singleton(){
   }

   private static Singleton singleton = null;

   public static Singleton getInstance(){
      if(null == singleton){
         singleton = new Singleton();
      }
      return singleton;
   }
   public String otherOperation(){
      //方法实现
   }
}
```

 

**Client:**

 

```
String str = Singleton.getInstance().otherOperation();
```

 

多线程时使用 double-check 模式确保线程安全:

 

```
class Singleton{
   
   private Singleton(){
   }
   private static Singleton singleton = null;
   public static Singleton getInstance(){
      if(null == singleton)
         sychronized (Singleton.class){
          if(null == singleton){
             singleton = new Singleton();
          }
       }
    }
    return singleton;
  }
}
```