设计模式笔记之一 单例模式

本文深入探讨单例模式的实现策略,包括预先实例化、懒加载和双重检查等方法,并分析各自优缺点及性能考量。通过对比实例,揭示如何在不同场景下选择合适的单例模式实现,以提升程序效率与可维护性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 
 
public class singleton {		/**	 * 预先实例化好了,也可以使用懒实例化,在构造函数中实例化,不过要注意线程同步的位码头	 */	private static singleton singleton = new singleton();		/**	 * 私有构造函数	 */	private singleton() {			}		/**	 * 对外接口	 * @return	 */	public static singleton getinstance() {				return singleton;	}}
 
例子2 懒实例化的单例模式
 
/** * 使用懒加载方式 */public class singleton2 {		private static singleton2 singleton2 = null;		private singleton2() {			}		/**	 * 缺点是每次都要判断是否为null,而且同步浪费效率	 */	public synchronized static singleton2 getinstance() {				if (singleton2 == null) {			singleton2 = new singleton2();		}		return singleton2;	}}
  
例子3 双重成例检查的单例模式
 
/** * 使用双重成例检查的单例模式 */public class singleton3 {	private static singleton3 singleton3 = null;		private singleton3() {			}		/**	 * 只会判断一次null,效率高了,但是代码稍微复杂了一点	 */	public static singleton3 getinstance() {				if (singleton3 == null) {						synchronized (singleton3.class) {								if (singleton3 == null) {					singleton3 = new singleton3();				}			}		}				return singleton3;	}	}
  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值