设计模式之单例模式(Singleton)

单例模式通常用于整个应用只存在一个类的实例的场景。单例模式分为懒汉式与饿汉式,实现的方式可以通过普通的class,也可以通过enum实现。

1、饿汉式:

对于应用启动后的访问响应时间要求高的应用可以尝试使用,性能消耗主要在创建对象上。

/**
 * 单例模式,饿汉式。
 * @author jim
 *
 */
public class ApplicationCacheSingleton1 {
	
	/**
	 * 加载类时进行对象创建。
	 */
	private static ApplicationCacheSingleton1 instance = new ApplicationCacheSingleton1();
	
	/**
	 * 返回实例。
	 * @return ApplicationCacheSingleton1实例
	 */
	public static ApplicationCacheSingleton1 getInstance(){
		return instance;
	}
}


2、懒汉式

侧重于按需创建,避免不必要的实例创建与维护。

/**
 * 单例模式,支持对象序列化,懒汉式。
 * @author jim
 *
 */
public class ApplicationCacheSingleton implements Serializable{
	
	/**
	 * UID
	 */
	private static final long serialVersionUID = 1420731236246142089L;
	/**
	 * 持有实例。
	 */
	private static ApplicationCacheSingleton instance;
	
	/**
	 * 获取实例,当实例不存在时创建。
	 * 采用Double-check进行实例创建。
	 * @return ApplicationCacheSingleton实例
	 */
	public static ApplicationCacheSingleton getInstance(){
		if (instance == null){
			initInstance();
		}
		
		return instance;
	}
	
	/**
	 * 实例化单实例成员变量。
	 */
	private synchronized static void initInstance(){
		if (instance == null){
			instance = new ApplicationCacheSingleton();
		}
	}
	
	/***
	 * 反序列化处理,确保类的实例只有一个。
	 * @return 对象实例
	 */
	private Object readResolve(){
		return instance;
	}

	/** 私有构造器,不允许外部实例化 */
	private ApplicationCacheSingleton() {
	}
}

另外一种通过enum实现单例,此种模式由enum自动保证序列化、反序列时单实例的存在。

/**
 * 通过Enum实现单例模式,其自动处理了反序列化单例的问题。
 * @author jim
 *
 */
public enum EnumSingleton {
	INSTANCE;
	public void getName(){
		return;
	}
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值