2、分别用饿汉式和懒汉式两种方式写出单例设计模式的程序懒汉式不考虑线程安全
饿汉式单例模式:
class Singleton(object):
instance = None
def __new__(cls, *args, **kwargs):
if not cls.instance:
cls.instance = super().__new__(cls)
return cls.instance
懒汉式单例模式(不考虑线程安全):
class Singleton(object):
instance = None
def __new__(cls, *args, **kwargs):
if not cls.instance:
cls.instance = super().__new__(cls)
return cls.instance
注意:上述懒汉式单例模式不考虑线程安全,如果在多线程环境下使用,可能会导致创建多个实例。如果需要考虑线程安全,请使用线程安全的方式实现懒汉式单例模式,例如使用加锁的方式
原文地址: https://www.cveoy.top/t/topic/hF0p 著作权归作者所有。请勿转载和采集!