单例模式通常用于整个应用只存在一个类的实例的场景。单例模式分为懒汉式与饿汉式,实现的方式可以通过普通的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;
}
}