码迷,mamicode.com
首页 > 其他好文 > 详细

单例模式

时间:2014-06-21 07:33:24      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:class   blog   java   get   strong      

      单例模式确保某个类只有一个实例,而且自行实例化并向整个系统提供这个实例。

      单例模式有三个要点:

      1.某个类只有一个实例

      2.这个类自行创建该实例

      3.这个类自行向整个系统提供这个实例

      多台电脑公用的打印机就是现实世界中单例模式的例子。

   

      恶汉式单例模式

public class EagerSingleton{
	private EagerSingleton(){		
	}
	
	private static final EagerSingleton instance = new EagerSingleton();
	
	public static EagerSingleton getInstance(){
		return instance;
	}
}

  懒汉式单例模式

public class LazySingleton{
	private LazySingleton(){		
	}
	
	private static LazySingleton instance = null;
	
	public synchronized static LazySingleton getInstance(){
		if(instance == null){
			instance = new LazySingleton();
		}
		return instance;
	}
}

  

单例模式,布布扣,bubuko.com

单例模式

标签:class   blog   java   get   strong      

原文地址:http://www.cnblogs.com/lnlvinso/p/3795438.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!