单例模式(Singleton)
单例对象(Singleton)是一种常用的设计模式。在Java应用中,单例对象能保证在一个JVM中,该对象只有一个实例存在。这样的模式有几个好处:
1、某些类创建比较频繁,对于一些大型的对象,这是一笔很大的系统开销。
2、省去了new操作符,降低了系统内存的使用频率,减轻GC压力。
3、有些类如交易所的核心交易引擎,控制着交易流程,如果该类可以创建多个的话,系统完全乱了。
//方法一
public class Singleton {
/* 私有构造方法,防止被实例化 */
private Singleton() {
}
/* 此处使用一个内部类来维护单例 */
private static class SingletonFactory {
private static Singleton instance = new Singleton();
}
/* 获取实例 */
public static Singleton getInstance() {
return SingletonFactory.instance;
}
/* 如果该对象被用于序列化,可以保证对象在序列化前后保持一致 */
public Object readResolve() {
return getInstance();
}
}
//方法二
public class Singleton {
//将自身的实例对象设置为一个属性,并加上Static和final修饰符
private static final Singleton instance = new Singleton();
//将构造方法设置成私有形式
private Singleton() {
}
//通过一个静态方法向外界提供这个类的实例
public static Singleton getInstance() {
return instance;
}
}
//方法三
class Singleton {
private static Singleton instance = null;
public static Singleton getInstance() {
if (instance == null) {
Synchronized (instance) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance2;
}
}
// 方法四
class Singleton {
private static Singleton instance = null;
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
注:四种方法实现了一样的功能,推荐采用第一、二种方法,第三、四种方法效率低(三高于四)。