大家好,我是 V 哥。再聊到单例模式,你可能会说老掉牙的问题有啥值得讲的,可能还真有,笔试题上镜率极高的一道题还在考,你的回答如何能从网络上千遍一律的回答中脱颖而出,成为卷王,是不是得来点不一样的东西呢,这 20 种单例模式的实现与变异总结,也许可以让你有新的发现,收藏起来吧。
单例设计模式确保一个类在整个系统中只存在一个实例,通常用于全局访问的共享资源,如数据库连接、配置文件读取、线程池等。以下 V 哥总结的 20 种不同的实现,来看一下:
1. 饿汉式(Eager Initialization)
public class SingletonEager {
private static final SingletonEager instance = new SingletonEager();
private SingletonEager() {}
public static SingletonEager getInstance() {
return instance;
}
}
复制代码
2. 懒汉式(Lazy Initialization)
public class SingletonLazy {
private static SingletonLazy instance;
private SingletonLazy() {}
public static SingletonLazy getInstance() {
if (instance == null) {
instance = new SingletonLazy();
}
return instance;
}
}
复制代码
3. 线程安全的懒汉式(Synchronized Lazy Initialization)
public class SingletonLazySync {
private static SingletonLazySync instance;
private SingletonLazySync() {}
public static synchronized SingletonLazySync getInstance() {
if (instance == null) {
instance = new SingletonLazySync();
}
return instance;
}
}
复制代码
4. 双重检查锁(Double-Checked Locking)
public class SingletonDCL {
private static volatile SingletonDCL instance;
private SingletonDCL() {}
public static SingletonDCL getInstance() {
if (instance == null) {
synchronized (SingletonDCL.class) {
if (instance == null) {
instance = new SingletonDCL();
}
}
}
return instance;
}
}
复制代码
5. 静态内部类(Static Inner Class)
实现:利用类加载机制,延迟创建实例。
特点:线程安全,懒加载,效率高。
public class SingletonInnerClass {
private SingletonInnerClass() {}
private static class Holder {
private static final SingletonInnerClass INSTANCE = new SingletonInnerClass();
}
public static SingletonInnerClass getInstance() {
return Holder.INSTANCE;
}
}
复制代码
6. 枚举单例(Enum Singleton)
public enum SingletonEnum {
INSTANCE;
public void someMethod() {
// some code
}
}
复制代码
7. 使用容器实现单例(Container Singleton)
import java.util.HashMap;
import java.util.Map;
public class SingletonContainer {
private static Map<String, Object> instanceMap = new HashMap<>();
private SingletonContainer() {}
public static void registerInstance(String key, Object instance) {
if (!instanceMap.containsKey(key)) {
instanceMap.put(key, instance);
}
}
public static Object getInstance(String key) {
return instanceMap.get(key);
}
}
复制代码
除了常见的 7 种实现方式,还有几种不同的单例模式变体,适合更复杂的使用场景:
8. 线程本地单例(ThreadLocal Singleton)
public class SingletonThreadLocal {
private static final ThreadLocal<SingletonThreadLocal> threadLocalInstance =
ThreadLocal.withInitial(SingletonThreadLocal::new);
private SingletonThreadLocal() {}
public static SingletonThreadLocal getInstance() {
return threadLocalInstance.get();
}
}
复制代码
9. CAS 实现的单例(CAS-based Singleton)
import java.util.concurrent.atomic.AtomicReference;
public class SingletonCAS {
private static final AtomicReference<SingletonCAS> INSTANCE = new AtomicReference<>();
private SingletonCAS() {}
public static SingletonCAS getInstance() {
while (true) {
SingletonCAS current = INSTANCE.get();
if (current != null) {
return current;
}
current = new SingletonCAS();
if (INSTANCE.compareAndSet(null, current)) {
return current;
}
}
}
}
复制代码
10. 枚举双重锁单例(Enum Holder with DCL)
public class SingletonEnumDCL {
private SingletonEnumDCL() {}
private enum Holder {
INSTANCE;
private final SingletonEnumDCL instance = new SingletonEnumDCL();
}
public static SingletonEnumDCL getInstance() {
return Holder.INSTANCE.instance;
}
}
复制代码
11. 注册表式单例(Registry Singleton)
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class SingletonRegistry {
private static final Map<String, Object> registry = new ConcurrentHashMap<>();
private SingletonRegistry() {}
public static void registerSingleton(String key, Object instance) {
registry.putIfAbsent(key, instance);
}
public static Object getSingleton(String key) {
return registry.get(key);
}
}
复制代码
12. Bill Pugh 单例(Bill Pugh Singleton)
public class SingletonBillPugh {
private SingletonBillPugh() {}
private static class SingletonHelper {
private static final SingletonBillPugh INSTANCE = new SingletonBillPugh();
}
public static SingletonBillPugh getInstance() {
return SingletonHelper.INSTANCE;
}
}
复制代码
13. 反射防护单例(Reflection Proof Singleton)
public class SingletonReflectionProof {
private static final SingletonReflectionProof INSTANCE = new SingletonReflectionProof();
private SingletonReflectionProof() {
if (INSTANCE != null) {
throw new IllegalStateException("Instance already created!");
}
}
public static SingletonReflectionProof getInstance() {
return INSTANCE;
}
}
复制代码
14. 资源管理单例(Resource Management Singleton)
public class SingletonResource {
private static final SingletonResource INSTANCE = new SingletonResource();
private SingletonResource() {
// 初始化资源
}
public static SingletonResource getInstance() {
return INSTANCE;
}
@Override
protected void finalize() throws Throwable {
super.finalize();
// 释放资源
}
}
复制代码
除了以上列出的常见单例模式实现方式,还有一些变种实现和特殊情况的单例设计。
下面介绍一些更高级的实现方式
15. 接口代理单例(Interface Proxy Singleton)
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class SingletonProxy {
private static final MySingletonInterface INSTANCE =
(MySingletonInterface) Proxy.newProxyInstance(
MySingletonInterface.class.getClassLoader(),
new Class[]{MySingletonInterface.class},
new SingletonHandler(new MySingleton())
);
private SingletonProxy() {}
public static MySingletonInterface getInstance() {
return INSTANCE;
}
private static class SingletonHandler implements InvocationHandler {
private final MySingleton instance;
public SingletonHandler(MySingleton instance) {
this.instance = instance;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 可以在这里加入权限控制、日志等
return method.invoke(instance, args);
}
}
}
interface MySingletonInterface {
void doSomething();
}
class MySingleton implements MySingletonInterface {
@Override
public void doSomething() {
System.out.println("Doing something...");
}
}
复制代码
16. Service Locator 单例(Service Locator Singleton)
import java.util.HashMap;
import java.util.Map;
public class ServiceLocator {
private static final Map<Class<?>, Object> services = new HashMap<>();
private ServiceLocator() {}
public static <T> void registerService(Class<T> serviceClass, T instance) {
services.put(serviceClass, instance);
}
@SuppressWarnings("unchecked")
public static <T> T getService(Class<T> serviceClass) {
return (T) services.get(serviceClass);
}
}
复制代码
17. 对象池单例(Object Pool Singleton)
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
public class SingletonObjectPool {
private static final int POOL_SIZE = 5;
private static final Queue<SingletonObjectPool> pool = new ConcurrentLinkedQueue<>();
static {
for (int i = 0; i < POOL_SIZE; i++) {
pool.add(new SingletonObjectPool());
}
}
private SingletonObjectPool() {}
public static SingletonObjectPool getInstance() {
SingletonObjectPool instance = pool.poll();
if (instance == null) {
instance = new SingletonObjectPool();
}
return instance;
}
public void release() {
pool.offer(this);
}
}
复制代码
18. 克隆防御单例(Clone-Proof Singleton)
public class SingletonCloneProof implements Cloneable {
private static final SingletonCloneProof INSTANCE = new SingletonCloneProof();
private SingletonCloneProof() {}
public static SingletonCloneProof getInstance() {
return INSTANCE;
}
@Override
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException("Cannot clone singleton instance");
}
}
复制代码
19. 定时刷新单例(Time-Based Singleton Refresh)
public class SingletonTimeBased {
private static SingletonTimeBased instance;
private static long lastCreatedTime = System.currentTimeMillis();
private static final long REFRESH_INTERVAL = 30000; // 30 seconds
private SingletonTimeBased() {}
public static synchronized SingletonTimeBased getInstance() {
if (instance == null || System.currentTimeMillis() - lastCreatedTime > REFRESH_INTERVAL) {
instance = new SingletonTimeBased();
lastCreatedTime = System.currentTimeMillis();
}
return instance;
}
}
复制代码
20. 弱引用单例(Weak Reference Singleton)
import java.lang.ref.WeakReference;
public class SingletonWeakReference {
private static WeakReference<SingletonWeakReference> instanceRef;
private SingletonWeakReference() {}
public static synchronized SingletonWeakReference getInstance() {
SingletonWeakReference instance = (instanceRef == null) ? null : instanceRef.get();
if (instance == null) {
instance = new SingletonWeakReference();
instanceRef = new WeakReference<>(instance);
}
return instance;
}
}
复制代码
最后
这些变种和扩展可以用来应对不同的使用场景,从安全性到性能需求再到资源管理需求。根据特定需求,可以选择或定制合适的单例实现方式。关注威哥爱编程,编程乐无边。
评论