1、私有化构造器
// Singleton with static factory
public class Elvis {private static final Elvis INSTANCE = new Elvis();private Elvis() { ... }public static Elvis getInstance() { return INSTANCE; }public void leaveTheBuilding() { ... }
}
可序列化对象单例(implements Serializable)
A、声明所有的实例属性为 transient
B、提供一个 readResolve 方法
// readResolve method to preserve singleton property
private Object readResolve() {// Return the one true Elvis and let the garbage collector// take care of the Elvis impersonator.return INSTANCE;
}
2、枚举单例
// Enum singleton - the preferred approach
public enum Elvis {INSTANCE;public void leaveTheBuilding() { ... }
}
枚举提供了免费的序列化机制,并提供了针对多个实例化的坚固保证,即使是在复杂的序列化或反射攻击的情况下。