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