`
从百草园到三味书屋
  • 浏览: 52885 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

设计模式之单例模式

阅读更多
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;
	}
}


分享到:
评论

相关推荐

    Java设计模式之单例模式的七种写法

    Java设计模式之单例模式的七种写法 单例模式是一种常见的设计模式,它确保某个类只有一个实例,而且自行实例化并向整个系统提供这个实例。在计算机系统中,线程池、缓存、日志对象、对话框、打印机的驱动程序对象常...

    python 设计模式之单例模式

    python 设计模式之单例模式

    设计模式之单例模式详解.pdf

    设计模式之单例模式详解 单例模式是一种常用的软件设计模式,其定义是单例对象的类只能允许一个实例存在。许多时候整个系统只需要拥有一个的全局对象,这样有利于我们协调系统整体的行为。 单例模式的实现主要是...

    研磨设计模式之单例模式

    通过研磨设计模式之单例模式的资料,你可以深入理解单例模式的原理、实现方式及其优缺点,进一步提升自己的编程技能和设计思维。学习并熟练掌握设计模式,对于成为一名优秀的Java开发者至关重要。

Global site tag (gtag.js) - Google Analytics