java和python单例模式的10种写法

2023-03-18 11:51:08 浏览数 (1)

  1. 懒汉模式(线程不安全)
代码语言:javascript复制
javaCopy codepublic class Singleton {
    private static Singleton instance;
    private Singleton() {}
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}
  1. 饿汉模式(线程安全)
代码语言:javascript复制
javaCopy codepublic class Singleton {
    private static final Singleton instance = new Singleton();
    private Singleton() {}
    public static Singleton getInstance() {
        return instance;
    }
}
  1. 双重检查锁模式(线程安全)
代码语言:javascript复制
javaCopy codepublic class Singleton {
    private volatile static Singleton instance;
    private Singleton() {}
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
  1. 静态内部类模式(线程安全)
代码语言:javascript复制
javaCopy codepublic class Singleton {
    private Singleton() {}
    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }
    public static Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}
  1. 枚举模式(线程安全)
代码语言:javascript复制
javaCopy codepublic enum Singleton {
    INSTANCE;
    public void whateverMethod() {}
}
  1. ThreadLocal模式(线程安全)
代码语言:javascript复制
javaCopy codepublic class Singleton {
    private static final ThreadLocal<Singleton> threadLocalInstance = new ThreadLocal<Singleton>(){
        @Override
        protected Singleton initialValue() {
            return new Singleton();
        }
    };
    private Singleton() {}
    public static Singleton getInstance() {
        return threadLocalInstance.get();
    }
}
  1. Holder模式(线程安全)
代码语言:javascript复制
javaCopy codepublic class Singleton {
    private Singleton() {}
    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }
    public static Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}
  1. 构造器模式(线程安全)
代码语言:javascript复制
javaCopy codepublic class Singleton {
    private static final Singleton INSTANCE;
    static {
        try {
            INSTANCE = new Singleton();
        } catch (Exception e) {
            throw new RuntimeException("Cannot create an instance of Singleton", e);
        }
    }
    private Singleton() {}
    public static Singleton getInstance() {
        return INSTANCE;
    }
}
  1. 反射攻击保护模式(线程安全)
代码语言:javascript复制
javaCopy codepublic class Singleton {
    private static final Singleton INSTANCE = new Singleton();
    private Singleton() {
        if (INSTANCE != null) {
            throw new IllegalStateException("Singleton instance already created.");
        }
    }
    public static Singleton getInstance() {
        return INSTANCE;
    }
    protected Object readResolve() throws ObjectStreamException {
        return INSTANCE;
    }
}
  1. CAS模式(线程安全)
代码语言:javascript复制
javaCopy codepublic class Singleton {
    private static final AtomicReference<Singleton> INSTANCE = new AtomicReference<>();
    private Singleton() {}
    public static Singleton getInstance() {
        for (;;) {
            Singleton instance = INSTANCE.get();
            if (instance != null) {
                return instance;
            }
            instance = new Singleton();
            if (INSTANCE.compareAndSet(null, instance)) {
                return instance;
            }
        }
    }
}

Python单例模式的10种写法:

  1. 模块级别变量
代码语言:javascript复制
pythonCopy codeclass Singleton:
    pass
singleton = Singleton()
  1. 基于__new__方法
代码语言:javascript复制
pythonCopy codeclass Singleton:
    _instance = None
    def __new__(cls):
        if not cls._instance:
            cls._instance = super().__new__(cls)
        return cls._instance
  1. 基于装饰器的实现
代码语言:javascript复制
pythonCopy codedef singleton(cls):
    instances = {}
    def get_instance(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]
    return get_instance
@singleton
class MyClass:
    pass
  1. 基于元类的实现
代码语言:javascript复制
pythonCopy codeclass Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super().__call__(*args, **kwargs)
        return cls._instances[cls]
class MyClass(metaclass=Singleton):
    pass
  1. 基于共享属性的实现
代码语言:javascript复制
pythonCopy codeclass Singleton:
    _shared_state = {}
    def __init__(self):
        self.__dict__ = self._shared_state
        self.state = 'initial state'
singleton = Singleton()
  1. 基于__dict__属性的实现
代码语言:javascript复制
pythonCopy codeclass Singleton:
    def __new__(cls):
        if not hasattr(cls, 'instance'):
            cls.instance = super().__new__(cls)
        return cls.instance
singleton = Singleton()
  1. 基于类装饰器的实现
代码语言:javascript复制
pythonCopy codedef singleton(cls):
    instance = cls()
    instance.__call__ = lambda: instance
    return instance
@singleton
class MyClass:
    pass
  1. 基于闭包的实现
代码语言:javascript复制
pythonCopy codedef singleton(cls):
    instances = {}
    def get_instance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]
    return get_instance
@singleton
class MyClass:
    pass
  1. 基于模块导入的实现
代码语言:javascript复制
pythonCopy codeclass Singleton:
    pass
singleton = Singleton()
# module.py
from singleton import singleton
  1. 基于单例模式的装饰器
代码语言:javascript复制
pythonCopy codedef singleton(cls):
    instances = {}
    def get_instance(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]
    return get_instance
@singleton
class MyClass:
    pass

分享

Regenerate response

0 人点赞