单例模式

单例模式的特点:

  1. 一个类只能有一个实例
  2. 类自己创建这个实例
  3. 整个系统都共同使用这个实例

单例模式分为:

  1. 懒汉式:类一加载就创建对象,上来就new一个不可修改的类对象,再来一个空的私有构造方法,和一个公有的入口(返回值是类对象)
  2. 饿汉式:用的时候,才去创建对象,声明一个为空的对象,在调用时new一个新的对象

以上两种情况在多线程下是不安全的,因为new对象是非原子性的,重排序问题会造成多线程下不安全

1.饿汉模式

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

2.懒汉模式-单线程版

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

3.懒汉模式-多线程版-性能低

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

4.懒汉模式-多线程版-二次判断-性能高

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

版权声明:本文为WallisEdward原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。