前言
这漠北风沙的回音
到底滚烫了谁的爱情
我不敢靠近
前世的风景
简介
设计模式(Design Pattern)是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结,使用设计模式是为了可重用代码、让代码更容易被他人理解并且保证代码可靠性。
单例模式
单例模式是确保一个类在内存中只能有一个对象存在,由自身初始化实例并向整个系统提供这个实例。
初始化
- 懒汉式
public class LazyInstance {
private static LazyInstance instance;
private LazyInstance() {
}
public static synchronized LazyInstance getInstance() {
if (instance == null) {
instance = new LazyInstance();
}
return instance;
}
}
- 饿汉式
public class HungryInstance {
private static final HungryInstance INSTANCE = new HungryInstance();
private HungryInstance() {
}
public static HungryInstance getInstance() {
return INSTANCE;
}
}
- 内部类
public class InnerClassInstance {
private InnerClassInstance() {
}
public static InnerClassInstance getInstance() {
return SingleHolder.INSTANCE;
}
private static class SingleHolder {
private static final InnerClassInstance INSTANCE = new InnerClassInstance();
}
}
- 双重加锁
public class DoubleCheckInstance {
private static volatile DoubleCheckInstance instance;
private DoubleCheckInstance() {
}
public static DoubleCheckInstance getInstance() {
if (instance == null) {
synchronized (DoubleCheckInstance.class) {
if (instance == null) {
instance = new DoubleCheckInstance();
}
}
}
return instance;
}
}
- 枚举
public enum EnumInstance {
INSTANCE
}