前言
可以复用的东西都叫做模式
关于将类设计成abstract还是interface,要看是抽象的概念还是特性(共有的特性)。抽象概念就用abstract,特性就用interface。无法明显区分abstract还是interface就用interface
单例
- 饿汉模式
public class EagerSingleton {
// jvm保证在任何线程访问uniqueInstance静态变量之前一定先创建了此实例
private static EagerSingleton uniqueInstance = new EagerSingleton();
// 私有的默认构造子,保证外界无法直接实例化
private EagerSingleton() {
}
// 提供全局访问点获取唯一的实例
public static EagerSingleton getInstance() {
return uniqueInstance;
}
}
- 懒汉模式
public class LazySingleton {
private static LazySingleton uniqueInstance;
private LazySingleton() {
}
public static synchronized LazySingleton getInstance() {
if (uniqueInstance == null)
uniqueInstance = new LazySingleton();
return uniqueInstance;
}
}
- 双检锁(不建议使用,性能)
public class DoubleCheckedLockingSingleton {
// java中使用双重检查锁定机制,由于Java编译器和JIT的优化的原因系统无法保证我们期望的执行次序。
// 在java5.0修改了内存模型,使用volatile声明的变量可以强制屏蔽编译器和JIT的优化工作
private volatile static DoubleCheckedLockingSingleton uniqueInstance;
private DoubleCheckedLockingSingleton() {
}
public static DoubleCheckedLockingSingleton getInstance() {
if (uniqueInstance == null) {
synchronized (DoubleCheckedLockingSingleton.class) {
if (uniqueInstance == null) {
uniqueInstance = new DoubleCheckedLockingSingleton();
}
}
}
return uniqueInstance;
}
}
改进
public class Singleton {
private static Singleton instance;
private Singleton() {
}
public static Singleton GetInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
占位符方式
public class LazyInitHolderSingleton {
private LazyInitHolderSingleton() {
}
private static class SingletonHolder {
private static final LazyInitHolderSingleton INSTANCE = new LazyInitHolderSingleton();
}
public static LazyInitHolderSingleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
枚举
public enum SingletonClass
{
INSTANCE;
}