单例模式:是对象的创建模式,它确保某个类只有一个实例,而且自行实例化并向整个系统提供这个实例。
单例对象持有对自己的引用。
饿汉式单例类:
public class EagerSingleton {
private static final EagerSingleton m_instance =
new EagerSingleton();
// 私有的默认构造子
private EagerSingleton() {}
// 静态工厂方法
public static EagerSingleton getInstance() {
return m_instance;
}
}
在这个类被加载时,静态变量m_instance会被初始化。
由于构造子是私有的,因此此类不能被继承。
懒汉式单例类:
与饿汉式单利类不同的是,懒汉式单例类在第一次被引用时将自己实例化。
public class LazySingleton {
private static LazySingleton m_instance = null;
private LazySingleton() {}
synchronized public static LazySingleton getInstance() {
if (m_instance == null) {
m_instance = new LazySingleton();
}
return m_instance;
}
}
资源利用效率:懒汉式 > 饿汉式
速度和反应时间:饿汉式 > 懒汉式
======================================
下面是Head First Patterns书中我总结的单例
public class Singleton {
/*
* 这种方法在多线程环境下会出问题,可以在getInstance()方法前加一个synchronized修饰符,不过又会造成性能问题,因为只有第一次(uniqueInstance没被初始化时)才需要同步
private static Singleton uniqueInstance;
private Singleton() {}
public static Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
*/
/*
* 急切方式。该方式解决了多线程问题
private static Singleton uniqueInstance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return uniqueInstance;
}
*/
/**双重检查加锁**/
// volatile关键字确保当uniqueInstance变量被初始化成Singleton实例时,多个线程正确地处理uniqueInstance变量
private volatile static Singleton uniqueInstance;
private Singleton() {}
public static Singleton getInstance() {
if (uniqueInstance == null) {
synchronized(Singleton.class) {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}
======================================