java和python单例模式的10种写法
【摘要】 懒汉模式(线程不安全)javaCopy codepublic class Singleton { private static Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { ...
- 懒汉模式(线程不安全)
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
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)