当前位置:首页 > 开发 > 编程语言 > 编程 > 正文

单例模式

发表于: 2015-04-19   作者:香水浓   来源:转载   浏览:
摘要: 懒汉  调用getInstance方法时实例化 public class Singleton { private static Singleton instance; private Singleton() {} public static synchronized Singleton getInstance() { if(null == ins
懒汉  调用getInstance方法时实例化
public class Singleton {

	private static Singleton instance;
	
	private Singleton() {}

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

}


饿汉  类加载时实例化
public class Singleton {

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

	public static Singleton getInstance() {
		return instance;
	}

}


public class Singleton {

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

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


静态内部类  调用getInstance方法时实例化
public class Singleton {

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

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


枚举
public enum Singleton {

	instance;
	
	public void fun() {
		//
	}
	
}


双重校验锁
public class Singleton {

	private volatile static Singleton instance;

	private Singleton() {
	}

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

}


Note:文章转自互联网

单例模式

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号