Python设计模式1--单例模式

    xiaoxiao2022-06-28  79

    设计模式的重要性,不再赘述,分方法和类型逐一记录,以备忘。

    一、单例模式

     单例模式,顾名思义,python中的某个类有且仅有一个对象(实例);

    1.应用场景:某个实例必须保证全局唯一性,如读取某些配置文件的实例,需要确保在任意地方都是相同配置值;

    2.实现方法:使用python中的基类object中__new__();

    3.代码:

    class singleton(object): def __new__(cls,*args,**kw): if not hasattr(cls,'_instance'): cls._instance = super(singleton,cls).__new__(cls) #call the object.__new__() return cls._instance class CExample(singleton): sharp="Ball" if __name__ == "__main__": e1=CExample() print(e1.sharp) e1.sharp='circle' e2=CExample() print(e2.sharp) print(id(e1)==id(e2)) #output ball circle True

     

     

     


    最新回复(0)