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

举报
赵KK日常技术记录 发表于 2023/06/24 20:44:13 2023/06/24
【摘要】 ​懒汉模式(线程不安全)javaCopy codepublic class Singleton { private static Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { ...

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

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。