Java中单例七种写法(懒汉、恶汉、静态内部类、双重检验锁、枚举)


/***
 * 懒汉模式 1
 * 可以延迟加载,但线程不安全。
 * @author admin
 *
 */
public class TestSinleton1 {
	private static  TestSinleton1 sinleton;
	private TestSinleton1(){
		
	}
	public static  TestSinleton1 getSinleton(){
		if(sinleton==null){
			return new TestSinleton1();
		}
		return sinleton;
	}
}
/***
 * 懒汉模式变种 2
 * @author admin
 * 使用了synchronized关键字,既可以延迟加载,又线程安全,但是执行效率低。
 */
class TestSinleton2{
	private static  TestSinleton2 sinleton;
	private TestSinleton2(){
		
	}
	public  synchronized static  TestSinleton2 getSinleton(){
		if(sinleton==null){
			return new TestSinleton2();
		}
		return sinleton;
	}
}
/***
 * 饿汉模式 3
 * @author admin
 * 基于classload机制,静态变量在类装载时进行初始化
 * 可以避免线程安全问题,但是没有延迟加载。
 */
class TestSinleton3{
	private static  TestSinleton3 sinleton = new TestSinleton3();
	private TestSinleton3(){
	}
	public static TestSinleton3 getSinleton(){
		return sinleton;
	}
}
/***
 * 恶汉变种模式 4
 * @author admin
 * 基于静态 代码块,在实例化或者第一次调用时执行
 * 既可以延迟加载,又线程安全
 */
class TestSinleton4{
	private static  TestSinleton4 sinleton =null;
	static{
		sinleton = new TestSinleton4();
	}
	public static TestSinleton4 getSinleton(){
		return sinleton;
	}
}
/***
 * 双重校验锁 5
 * @author admin
 * 懒汉模式的优化版,拥有线程安全、高效率以及延迟加载等特性。但是这种方式需要jdk1.5以上,且在一些平台和编译器下有错。
 */
class TestSinleton5{
	private static volatile TestSinleton5 sinleton;
	private TestSinleton5(){
		
	}
	public static TestSinleton5 getSinleton(){
		if(sinleton==null){
			synchronized (TestSinleton5.class) {
				if(sinleton==null){
					
					sinleton = new  TestSinleton5();
				}
			}
		}
		return sinleton;
	}
}
/***
 * 静态内部类 6
 * @author admin
 * 恶汉模式的优化版,在类被装载时,静态内部类并没有被实例化,
 * 只有getInstance()时才 会装载 SingletonHolder 类,静态内部类方式也能很好地,实现线程安全、高效率和延迟加载特性。
 */
class TestSinleton6{
	private static class SingletonHolder {
		private static final TestSinleton6 sinleton = new TestSinleton6();
	}
	private TestSinleton6(){}
	public static final TestSinleton6 getSinleton(){
		return SingletonHolder.sinleton;
	}
	
}
/***
 * 枚举7
 * @author admin
 *避免多线程同步问题
 */
enum TestSinleton7 {
	SINLETON;
}

  

优质内容筛选与推荐>>
1、Python网络编程之 select
2、LeetCode(41)First Missing Positive
3、不得了,微软原生提供 AI 人工智能 API,而且面向网页开放
4、05-表的操作
5、加速软件源更新和安装 ubuntu 软件中心


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号