---
title: "设计模式之单例模式"
author: "从百草园到三味书屋"
date: "2013-01-18T17:19:12Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2013-01-18T17:20:17Z"
id: 1772258
url: "https://firethemax.iteye.com/blog/1772258"
---

```java
package singleton;

public class Singleton {

	
}

/**
 * 适用于单线程环境
 *
 * @author  
 * @since   Pattern 1.0.0
 * @created 2013-1-6
 */
class SingletonOne{
	
	private static SingletonOne instance = null;
	
	private SingletonOne(){}
	
	public static SingletonOne getInstance(){
		if(instance==null){
			instance = new SingletonOne();
		}
		return instance;
	}
}

/**
 * 适用于多线程环境，但是该同步机制会对性能造成一定的下降
 *
 * @author  meiquan_yang
 * @since   Pattern 1.0.0
 * @created 2013-1-6
 */
class SingletonTwo{
	
	private static SingletonTwo instance = null;
	
	private SingletonTwo(){}
	
	public static synchronized SingletonTwo getInstance(){
		if(instance==null){
			instance = new SingletonTwo();
		}
		return instance;
	}
	
}

/**
 * 适用于多线程环境，采用Double-check Locking方式检测，只有在第一次实例化的时候才进入同步块,
 * 为了保证内存可见性，instance最好加上volatile关键字。
 *
 * @author  meiquan_yang
 * @since   Pattern 1.0.0
 * @created 2013-1-6
 */
class SingletonThree{
	
	private static volatile SingletonThree instance = null;
	
	private SingletonThree(){
		//...
	}
	
	public static SingletonThree getInstance(){
		if(instance==null){
			synchronized (SingletonThree.class) {
				if(instance==null){
					instance = new SingletonThree();
				}
			}
		}
		return instance;
	}
}

/**
 * 即是延迟加载，又能保证多线程环境下单例。
 *
 * @author  meiquan_yang
 * @since   Pattern 1.0.0
 * @created 2013-1-6
 */
class SingletonFour{
	
	private static class SingletonHolder{
		private final static SingletonFour instance = new SingletonFour();
	}
	
	private SingletonFour(){}
	
	public static SingletonFour getInstance(){
		return SingletonHolder.instance;
	}
}



```