---
title: "三种单利模式"
author: "2007yn"
date: "2009-12-17T11:53:48Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2009-12-17T11:53:48Z"
id: 550398
url: "https://2007yn.iteye.com/blog/550398"
---

模式一:

```
class Singleton2 {
 
 private Singleton2(){
 }
 
 private static Singleton2 instance;

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

}

```

 

不用说,大家也知道,这种在单线程程序中是没什么问题的,但多线程程序中,则可能会创建出2个或多个对象.

不同步的话， 对于懒汉式的， 就是在， 这个类的实例还没有创建的时候， 2个线程同时去调用getInstance, 这时， 由于没有同步锁， 有可能会创建出2个实例来。  
对于饿汉式， 由于实例是在load class的时候创建的， 所以就没有这个问题。 当然， 就是2个线程采用了不同的class loader.  
当然， 无论饿汉还是懒汉， 几率都不高， 但几率低不代表不会出错， 逻辑上也不对， 因此， 编程者还是应该避免。

模式二:

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

}

```

 

这种很显然没有前者的问题.

模式三:

```
public class Singleton {

 private static class SingletonHolder {
  static Singleton instance = new Singleton();
 }

 public static Singleton getInstance() {
  return SingletonHolder.instance;
 }

}

```

 

在模式2中,不管我们是不是调用getInstance()都会存在一个实例在内存中,而在模式3中,  
只有我们调用了getInstance(),才会创建唯一的实例到内存中.并且也解决了模式1中多线程的问题.  
解决的方式是利用了Classloader的特性