设置模式之 -> 单例模式

版本1

package com.dp;

public class Singleton {
	private Singleton() {
		// TODO Auto-generated constructor stub
	}
	
	private static Singleton instance = new Singleton();
	
	private static Singleton getInstance() {
		return instance;
	}
}

版本2 较版本1,实现了懒加载

package com.dp;

public class Singleton {
	private Singleton() {
		// TODO Auto-generated constructor stub
	}
	
	private static Singleton instance = null;
	
	private static synchronized Singleton getInstance() {
		if (instance == null)
			instance = new Singleton();
		return instance;
	}
}

版本3 较版本2,优化了同步带来的性能损耗

package com.dp;

public class Singleton {
	private Singleton() {
		// TODO Auto-generated constructor stub
	}
	
	private static class SingletonHolder {
		private static Singleton instance = new Singleton();
	}
	
	public static Singleton getInstance() {
		return SingletonHolder.instance;
	}
}
发布了176 篇原创文章 · 获赞 1 · 访问量 7184

猜你喜欢

转载自blog.csdn.net/qq_37769323/article/details/104172932