设计模式(一) 单例设计模式

单例设计模式:

定义:保证类在内存中只有一个对象。

步骤:

1.私有构造方法

2.创建唯一对象

3.对外仅提供访问方法


最常见的2种方法:

 懒汉式与饿汉式 两者区别:

饿汉式:线程安全,空间换时间,不能延迟加载

public class SingletonHungry {
	private SingletonHungry(){}
	private static SingletonHungry singletonHungry = new SingletonHungry();
	private static SingletonHungry getInstance(){
		return singletonHungry;
	}
}

懒汉式:线程不安全,时间换空间,可以延迟加载

public class SingletonLazy {
	private SingletonLazy(){}
	private static SingletonLazy singletonLazy;
	private static synchronized SingletonLazy getInstance(){
		if(singletonLazy==null){
			singletonLazy = new SingletonLazy();
		}
		return singletonLazy;
	}
}

其他方法:

1.双重检测锁式:

public class SingletonDoubleLock {
	private SingletonDoubleLock(){}
	private static SingletonDoubleLock instance =null;
	
	public static SingletonDoubleLock getInstance(){
		if(instance==null){
			SingletonDoubleLock singletonDoubleLock;
			synchronized (SingletonDoubleLock.class){
				singletonDoubleLock = instance;
				if(singletonDoubleLock==null){
					synchronized(SingletonDoubleLock.class){
						if(singletonDoubleLock==null){
							singletonDoubleLock = new SingletonDoubleLock();
						}
					}
				}
			}
			return singletonDoubleLock;
		}
		return instance;
	}
}


2.静态内部类式:线程安全,调用效率高,可以延迟加载

public class SingletonStatic {
	
	private SingletonStatic(){}
	
	private static class SingletonClassInstance{
		private static final SingletonStatic singletonStatic = new SingletonStatic();
	}
	
	public static SingletonStatic getInstance(){
		return SingletonClassInstance.singletonStatic;
	}
}


3.枚举式:线程安全,调用效率高,不能延迟加载

public enum SingletonEnum {
	INSTANCE;
}






  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值