小Q:什么是设计模式
慢慢:设计模式是系统服务设计中针对常见场景的一种解决方案,可以解决功能逻辑开发中遇到的共性问题。设计模式并不局限最终的实现方案,而是在这种概念模式下,解决系统设计中的代码逻辑问题。
小Q:什么是单例模式
单例模式保证了不管何时使用,都是使用同一个对象实例。使用单例模式的好处在于:不用频繁的创建和销毁对象实例,减少资源的消耗。
小Q:赶快上代码!
单例模式的实现有很多种,但最终可以分为两类:懒汉模式和饿汉模式。
- 饿汉模式:及在程序启动时直接创建,不管以后是否有用到此对象实例。(会增大系统的开销)
public class Demo {
private Demo(){} // 只能调用 getInstance
private static Singleton instance = new Singleton(); // 在加载此类时直接创建
public static Singleton getInstance() {
return instance; 获取此对象
}
}
- 懒汉模式:懒汉模式会在我们需要时(及调用 getInstance()) 时才创建对象,这样如果没有使用就不会自动创建。懒汉模式又有多种的实现方案:
- 静态内部类模式
- 线程不安全模式
- 线程安全模式1
- 线程安全模式2(双重锁校验)
- 线程安全模式3(使用 CAS)
- 枚举模式
// 静态内部类模式
public class Demo {
private Demo(){} // 只能调用 getInstance
private static class SingletonInner{
private static Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonInner.instance;
}
}
// 线程不安全模式,此模式在高并发下会同时创建出多个实例
public class Demo {
private static Singleton instance;
private Demo(){} // 只能调用 getInstance
public static Singleton getInstance() {
if (instance == null)
instance = new Singleton();
return instance;
}
}
// 线程安全模式1,此模式下锁的粒度很高,需要进行优化
public class Demo {
private static Singleton instance;
private Demo(){} // 只能调用 getInstance
public synchronized static Singleton getInstance() {
if (instance == null)
instance = new Singleton();
return instance;
}
}
// 线程安全模式2:减低了锁的粒度,将 synchronized 从方法弄到代码段里,但需要有双重判断
// 因为当线程阻塞时,进行的线程会先创建实例,这时阻塞的线程放行后无需再创建
public class Demo {
private static Singleton instance;
private Demo(){} // 只能调用 getInstance
public static Singleton getInstance() {
if (instance == null) {
synchronized (Demo.class) {
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
// 线程安全模式3:使用原子类来保证线程安全
public class Demo {
private static final AtomicReference<Singleton> INSTANCE = new AtomicReference<Singleton>();
private static Singleton instance;
private Demo() {}
public static Singleton getInstance() {
for (;;) { // 自旋锁
Singleton instance = INSTANCE.get();
if (null == instance)
INSTANCE.compareAndSet(null, new Singleton());
else
return instance;
}
}
}
// 使用枚举
public enum Singleton {
INSTANCE;
public void doSomething() {
System.out.println("doSomething");
}
}
// 对于原先的模式,需要 Singleton 实例下的功能需要这样调用:Demo.getInstance().doSomething()
// 而枚举模式下的调用:Singleton.INSTANCE.doSomething
小Q:枚举类型这么难理解,还有必要学吗?
枚举的方式是美国著名程序员 Bloch 极力推荐的。它的实现代码简洁,即使在面对复杂的串行化或反射攻击时,也无偿提供了串行化机制。