zoukankan      html  css  js  c++  java
  • python 四种单例模式

     1  
     2 1 使用__new__方法
     3 Python
     4 class Singleton(object): def __new__(cls, *args, **kw): if not hasattr(cls, '_instance'): orig = super(Singleton, cls) cls._instance = orig.__new__(cls, *args, **kw) return cls._instanceclass MyClass(Singleton): a = 1
     5 
     6 
     7 
     8 
     9 
    10 class Singleton(object):
    11     def __new__(cls, *args, **kw):
    12         if not hasattr(cls, '_instance'):
    13             orig = super(Singleton, cls)
    14             cls._instance = orig.__new__(cls, *args, **kw)
    15         return cls._instance
    16  
    17 class MyClass(Singleton):
    18     a = 1
    19 2 共享属性
    20 创建实例时把所有实例的__dict__指向同一个字典,这样它们具有相同的属性和方法.
    21 
    22 Python
    23 class Borg(object): _state = {} def __new__(cls, *args, **kw): ob = super(Borg, cls).__new__(cls, *args, **kw) ob.__dict__ = cls._state return obclass MyClass2(Borg): a = 1
    24 
    25 
    26 
    27 
    28 
    29 
    30 class Borg(object):
    31     _state = {}
    32     def __new__(cls, *args, **kw):
    33         ob = super(Borg, cls).__new__(cls, *args, **kw)
    34         ob.__dict__ = cls._state
    35         return ob
    36  
    37 class MyClass2(Borg):
    38     a = 1
    39 3 装饰器版本
    40 Python
    41 def singleton(cls, *args, **kw): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls(*args, **kw) return instances[cls] return getinstance@singletonclass MyClass: ...
    42 
    43 
    44 
    45 
    46 
    47 
    48 def singleton(cls, *args, **kw):
    49     instances = {}
    50     def getinstance():
    51         if cls not in instances:
    52             instances[cls] = cls(*args, **kw)
    53         return instances[cls]
    54     return getinstance
    55  
    56 @singleton
    57 class MyClass:
    58   ...
    59 4 import方法
    60 作为python的模块是天然的单例模式
    61 
    62 Python
    63 # mysingleton.pyclass My_Singleton(object): def foo(self): passmy_singleton = My_Singleton()# to usefrom mysingleton import my_singletonmy_singleton.foo()
    64 
    65 
    66 
    67 # mysingleton.py
    68 class My_Singleton(object):
    69     def foo(self):
    70         pass
    71  
    72 my_singleton = My_Singleton()
    73  
    74 # to use
    75 from mysingleton import my_singleton
    76  
    77 my_singleton.foo()
  • 相关阅读:
    Solaris安装pkg
    JSP路径出现问题
    错误卸载软件导致Windows7系统中的软件无法播放视频
    蛋疼的Solaris设置
    SQL运行突然SESSION中断错误
    JAVA利用Zip4j解压缩
    java解压缩/压缩/加密压缩/加密解压缩 ZIP4J---ZIP文件压缩与解压缩学习
    未得冠军的运动员也有教练——Leo鉴书71
    VS2008 编译SQLite 3.8.4.3 + sqlcipher-3.1.0 + openssl-1.0.1g
    Android数据库安全解决方案,使用SQLCipher进行加解密
  • 原文地址:https://www.cnblogs.com/chengyunshen/p/7196280.html
Copyright © 2011-2022 走看看