- 懒汉模式(线程不安全)
javaCopy codepublic class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
- 饿汉模式(线程安全)
javaCopy codepublic class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
- 双重检查锁模式(线程安全)
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;
}
}
- 静态内部类模式(线程安全)
javaCopy codepublic class Singleton {
private Singleton() {}
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
- 枚举模式(线程安全)
javaCopy codepublic enum Singleton {
INSTANCE;
public void whateverMethod() {}
}
- ThreadLocal模式(线程安全)
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();
}
}
- Holder模式(线程安全)
javaCopy codepublic class Singleton {
private Singleton() {}
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
- 构造器模式(线程安全)
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;
}
}
- 反射攻击保护模式(线程安全)
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;
}
}
- CAS模式(线程安全)
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种写法:
- 模块级别变量
pythonCopy codeclass Singleton:
pass
singleton = Singleton()
- 基于__new__方法
pythonCopy codeclass Singleton:
_instance = None
def __new__(cls):
if not cls._instance:
cls._instance = super().__new__(cls)
return cls._instance
- 基于装饰器的实现
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
- 基于元类的实现
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
- 基于共享属性的实现
pythonCopy codeclass Singleton:
_shared_state = {}
def __init__(self):
self.__dict__ = self._shared_state
self.state = 'initial state'
singleton = Singleton()
- 基于__dict__属性的实现
pythonCopy codeclass Singleton:
def __new__(cls):
if not hasattr(cls, 'instance'):
cls.instance = super().__new__(cls)
return cls.instance
singleton = Singleton()
- 基于类装饰器的实现
pythonCopy codedef singleton(cls):
instance = cls()
instance.__call__ = lambda: instance
return instance
@singleton
class MyClass:
pass
- 基于闭包的实现
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
- 基于模块导入的实现
pythonCopy codeclass Singleton:
pass
singleton = Singleton()
# module.py
from singleton import singleton
- 基于单例模式的装饰器
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