Singleton 单例模式

   

   Singleton模式在Java中是一个最经常使用的模式。它是用来防止经过外部控制建立的对象实例化。这个概念能够推广到系统时更有效率地运做只存在一个对象或对象的实例化限制在必定数量,例如:java

   1.私有构造函数-没有其余的类能够实例化一个新对象。ide

   2.属性私有化。函数

   3.惟一获取对象,经过静态公共方法获取。spa

Class Diagram and Codecode

      singleton

第一种:对象

public class AmericaPresident {
	private static final AmericaPresident thePresident = new AmericaPresident(); 	private AmericaPresident() {} 	public static AmericaPresident getPresident() {
		return thePresident;
	}}

第二种:ci

public class AmericaPresident {
	private static AmericaPresident thePresident; 	private AmericaPresident() {} 	public static AmericaPresident getPresident() {
		if (thePresident == null) {
			thePresident = new AmericaPresident();
		}
		return thePresident;
	}}

第三种:get

public enum AmericaPresident{
	INSTANCE; 	public static void doSomething(){
		//do something
	}}
相关文章
相关标签/搜索