java单例

1. 饿汉模式

class SingletonHungary {
	//由于只能 new一次 先私有化构造器 通提供方法访问
	//static 方法类只能访问 static 属性
	private static SingletonHungary singletonHungary = new SingletonHungary();
	//将构造器设置为private禁止通过new进行实例化
	private SingletonHungary() {	
	}
	// 静态全局化  提供get方法
	public static SingletonHungary getInstance() {
		return singletonHungary;
	}
}

2. 懒汉模式

// 单例模式的懒汉实现1--线程不安全
class SingletonLazy {
	private static SingletonLazy singletonLazy;
	private SingletonLazy() {

	}
	public static SingletonLazy getInstance() {
		//判断singletonLazy 是否被 new过 new过一次就不会在new新的singletonLazy
		if (null == singletonLazy) {
			singletonLazy = new SingletonLazy();
		}
		return singletonLazy;
	}
}

3.双锁式

class SingletonLazy{
	private static SingletonLazy singletonLazy;//singletonLazy修饰被不同线程访问和修改的变量
	private SingletonLazy(){}
	public static SingletonLazy getInstance(){
	   // 先判断实例是否存在,若不存在再对类对象进行加锁处理
	if(singletonLazy==null){
		synchronized(SingletonLazy.class){//对整个类加锁
			if(singletonLazy==null){
				singletonLazy=new SingletonLazy();
			}
		}	
	}
	return singletonLazy;
	}
}

4.类部类式

class SingletonHungary {

	private SingletonHungary() {	
	}
	private static class SingletonHungary2{
		private static SingletonHungary singletonHungary = new SingletonHungary();
	}
	public static SingletonHungary getInstance() {
		return SingletonHungary2.singletonHungary;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值