单例模式的3种写法

  • 懒汉式(被调用时才实例化)
public class SingleTon {
     

	private static SingleTon singleton;

	private SingleTon() {
     
	}

	public static SingleTon getInstance() {
     
		// 添加逻辑如果实例化过,直接返回
		if (singleton == null) {
     
			// 多线程访问下,可能出现 if 同时成立的情况,添加锁
			synchronized (SingleTon.class) {
     
				// 双重验证
				if (singleton == null) {
     
					singleton = new SingleTon();
				}
			}
		}
		return singleton;
	}
	//懒汉式添加了锁,效率低
}
  • 饿汉式(类被加载时实例化)
public class SingleTon {
     

	private static SingleTon singleton = new SingleTon();

	private SingleTon() {
     
	}

	public static SingleTon getInstance() {
     
		return singleton;
	}
	
}
  • 内部类实现单例
public class SingleTon {
     

	private SingleTon() {
     
	}

	private static class Inner {
     
		private static SingleTon t = new SingleTon();
	}

	public static SingleTon getInstance() {
     
		return Inner.t;
	}

}

你可能感兴趣的:(单例模式的3种写法)