栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

单例模式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

单例模式

单例模式思想:构造器私有

饿汉式:在加载的时候就实例化 容易造成资源的浪费

//饿汉式单例
public class Hungry {

	private Hungry() {
		
	}
	
	private final static Hungry HUNGRY = new Hungry();
	
	public static Hungry getInstance() {
		return HUNGRY;
	}
	
}

懒汉式:线程不安全

//懒汉式单例
public class LazyMan {

	private LazyMan() {
		
	}
	
	private static LazyMan lazyMan;
	
	public LazyMan getInstance() {
		if(lazyMan==null) {
			lazyMan = new LazyMan();
		}
		return lazyMan;
	}
	
	
}

DCL懒汉式:还是有问题指令重排导致出错

//懒汉式单例
public class LazyMan {

	private LazyMan() {
		
	}
	
	private static LazyMan lazyMan;
	
	// 双重检测锁模式 懒汉式单例 DCL懒汉式
	public LazyMan getInstance() {
		if(lazyMan==null) {
			synchronized (LazyMan.class) {
				if(lazyMan==null) {
					lazyMan = new LazyMan(); // 不是原子性操作
					
				}
			}
		}
		return lazyMan; 
	}
	
	
}

DCL懒汉式+volatile:

//懒汉式单例
public class LazyMan {

	private LazyMan() {
		
	}
	
	private volatile static LazyMan lazyMan;
	
	// 双重检测锁模式 懒汉式单例 DCL懒汉式
	public LazyMan getInstance() {
		if(lazyMan==null) {
			synchronized (LazyMan.class) {
				if(lazyMan==null) {
					lazyMan = new LazyMan(); 
				}
			}
		}
		return lazyMan; 
	}
	
	
}

静态内部类:

//静态内部类
public class Holder {
	
	private Holder() {
		
	}
	
	public static Holder getInstace() {
		return InnerClass.HOLDER;
	}
	
	public static class InnerClass{
		private static final Holder HOLDER = new Holder();
	}

}

枚举:

//枚举 enum本身也是一个Class类
public enum EnumSingle {
	
	INSTANCE;
	
	public EnumSingle getInstance() {
		return INSTANCE;
	}

}

单例不安全可以通过反射进行破坏

但是反射不能破坏枚举的单例模式

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/323090.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号