<output id="qn6qe"></output>

    1. <output id="qn6qe"><tt id="qn6qe"></tt></output>
    2. <strike id="qn6qe"></strike>

      亚洲 日本 欧洲 欧美 视频,日韩中文字幕有码av,一本一道av中文字幕无码,国产线播放免费人成视频播放,人妻少妇偷人无码视频,日夜啪啪一区二区三区,国产尤物精品自在拍视频首页,久热这里只有精品12

      Worth Waiting For

      單利模式的四種方式

      單利模式相關(guān)內(nèi)容

      內(nèi)容

      保證一個類只有一個實例,并提供一個訪問它的全局訪問點

      角色

      單利

      使用場景

      當(dāng)類只有一個實例而且客戶可以從一個眾所周知的訪問點訪問它時
      比如:數(shù)據(jù)庫鏈接、Socket創(chuàng)建鏈接

      優(yōu)點

      對唯一實例的受控訪問
      單利相當(dāng)于全局變量,但防止了命名空間被污染

      與單利模式功能相似的概念:全局變量、靜態(tài)變量(方法)

        試問?為什么用單例模式,不用全局變量呢?

        答、全局變量可能會有名稱空間的干擾,如果有重名的可能會被覆蓋

      單例模式的實現(xiàn)方式

      1、文件導(dǎo)入的形式(常用)

      s1.py
      
      class Foo(object):
          def test(self):
              print("123")
      
      v = Foo()
      #v是Foo的實例
      s2.py from s1 import v as v1 print(v1,id(v1)) #<s1.Foo object at 0x0000000002221710> 35788560 from s1 import v as v2 print(v1,id(v2)) #<s1.Foo object at 0x0000000002221710> 35788560 # 兩個的內(nèi)存地址是一樣的 # 文件加載的時候,第一次導(dǎo)入后,再次導(dǎo)入時不會再重新加載。

      2、基于類實現(xiàn)的單例模式

      # ======================單例模式:無法支持多線程情況===============
      
      class Singleton(object):
      
          def __init__(self):
              import time
              time.sleep(1)
      
          @classmethod
          def instance(cls, *args, **kwargs):
              if not hasattr(Singleton, "_instance"):
                  Singleton._instance = Singleton(*args, **kwargs)
              return Singleton._instance
      
      import threading
      
      def task(arg):
          obj = Singleton.instance()
          print(obj)
      
      for i in range(10):
          t = threading.Thread(target=task,args=[i,])
          t.start()
      
      
      # ====================單例模式:支持多線程情況================、
      
      import time
      import threading
      class Singleton(object):
          _instance_lock = threading.Lock()
      
          def __init__(self):
              time.sleep(1)
      
          @classmethod
          def instance(cls, *args, **kwargs):
              if not hasattr(Singleton, "_instance"):
                  with Singleton._instance_lock:   #為了保證線程安全在內(nèi)部加鎖
                      if not hasattr(Singleton, "_instance"):
                          Singleton._instance = Singleton(*args, **kwargs)
              return Singleton._instance
      
      
      def task(arg):
          obj = Singleton.instance()
          print(obj)
      for i in range(10):
          t = threading.Thread(target=task,args=[i,])
          t.start()
      time.sleep(20)
      obj = Singleton.instance()
      print(obj)

      # 使用先說明,以后用單例模式,obj = Singleton.instance()
      # 示例:
      # obj1 = Singleton.instance()
      # obj2 = Singleton.instance()
      # print(obj1,obj2)
      # 錯誤示例
      # obj1 = Singleton()
      # obj2 = Singleton()
      # print(obj1,obj2)

      3、基于__new__實現(xiàn)的單例模式(最常用)

      # =============單線程下執(zhí)行===============
      import threading
      class Singleton(object):
      
          _instance_lock = threading.Lock()
          def __init__(self):
              pass
      
          def __new__(cls, *args, **kwargs):
              if not hasattr(Singleton, "_instance"):
                  with Singleton._instance_lock:
                      if not hasattr(Singleton, "_instance"):
                          # 類加括號就回去執(zhí)行__new__方法,__new__方法會創(chuàng)建一個類實例:Singleton()
                          Singleton._instance = object.__new__(cls)  # 繼承object類的__new__方法,類去調(diào)用方法,說明是函數(shù),要手動傳cls
              return Singleton._instance  #obj1
              #類加括號就會先去執(zhí)行__new__方法,在執(zhí)行__init__方法
      # obj1 = Singleton()
      # obj2 = Singleton()
      # print(obj1,obj2)
      
      # ===========多線程執(zhí)行單利============
      def task(arg):
          obj = Singleton()
          print(obj)
      
      for i in range(10):
          t = threading.Thread(target=task,args=[i,])
          t.start()

      # 使用先說明,以后用單例模式,obj = Singleton()
      # 示例
      # obj1 = Singleton()
      # obj2 = Singleton()
      # print(obj1,obj2)

      4、基于metaclass(元類)實現(xiàn)的單例模式

      """
      1.對象是類創(chuàng)建,創(chuàng)建對象時候類的__init__方法自動執(zhí)行,對象()執(zhí)行類的 __call__ 方法
      2.類是type創(chuàng)建,創(chuàng)建類時候type的__init__方法自動執(zhí)行,類() 執(zhí)行type的 __call__方法(類的__new__方法,類的__init__方法)
      
      # 第0步: 執(zhí)行type的 __init__ 方法【類是type的對象】
      class Foo:
          def __init__(self):
              pass
      
          def __call__(self, *args, **kwargs):
              pass
      
      # 第1步: 執(zhí)行type的 __call__ 方法
      #        1.1  調(diào)用 Foo類(是type的對象)的 __new__方法,用于創(chuàng)建對象。
      #        1.2  調(diào)用 Foo類(是type的對象)的 __init__方法,用于對對象初始化。
      obj = Foo()
      # 第2步:執(zhí)行Foo的 __call__ 方法
      obj()
      """
      
      # ===========類的執(zhí)行流程================
      class SingletonType(type):
          def __init__(self,*args,**kwargs):
              print(self)  #會不會打印?  #<class '__main__.Foo'>
              super(SingletonType,self).__init__(*args,**kwargs)
      
          def __call__(cls, *args, **kwargs):  #cls = Foo
              obj = cls.__new__(cls, *args, **kwargs)
              obj.__init__(*args, **kwargs)
              return obj
      
      
      class Foo(metaclass=SingletonType):
          def __init__(self,name):
              self.name = name
          def __new__(cls, *args, **kwargs):
              return object.__new__(cls, *args, **kwargs)
      '''
          1、對象是類創(chuàng)建的,創(chuàng)建對象時類的__init__方法會自動執(zhí)行,對象()執(zhí)行類的__call__方法
          2、類是type創(chuàng)建的,創(chuàng)建類時候type類的__init__方法會自動執(zhí)行,類()會先執(zhí)行type的__call__方法(調(diào)用類的__new__,__init__方法)
          Foo 這個類是由SingletonType這個類創(chuàng)建的
      '''
      obj = Foo("hiayan")
      
      
      # ============第三種方式實現(xiàn)單例模式=================
      import threading
      
      class SingletonType(type):
          _instance_lock = threading.Lock()
          def __call__(cls, *args, **kwargs):
              if not hasattr(cls, "_instance"):
                  with SingletonType._instance_lock:
                      if not hasattr(cls, "_instance"):
                          cls._instance = super(SingletonType,cls).__call__(*args, **kwargs)
              return cls._instance
      
      class Foo(metaclass=SingletonType):
          def __init__(self,name):
              self.name = name
      
      
      obj1 = Foo('name')
      obj2 = Foo('name')
      print(obj1,obj2)

      單例模式的應(yīng)用

      (會在數(shù)據(jù)庫連接池中用到單例模式),詳見以下示例操作

      pool.py

      import pymysql
      import threading
      from DBUtils.PooledDB import PooledDB
      
      class SingletonDBPool(object):
          _instance_lock = threading.Lock()
      
          def __init__(self):
              self.pool = PooledDB(
                  creator=pymysql,  # 使用鏈接數(shù)據(jù)庫的模塊
                  maxconnections=6,  # 連接池允許的最大連接數(shù),0和None表示不限制連接數(shù)
                  mincached=2,  # 初始化時,鏈接池中至少創(chuàng)建的空閑的鏈接,0表示不創(chuàng)建
      
                  maxcached=5,  # 鏈接池中最多閑置的鏈接,0和None不限制
                  maxshared=3,
                  # 鏈接池中最多共享的鏈接數(shù)量,0和None表示全部共享。PS: 無用,因為pymysql和MySQLdb等模塊的 threadsafety都為1,所有值無論設(shè)置為多少,_maxcached永遠為0,所以永遠是所有鏈接都共享。
                  blocking=True,  # 連接池中如果沒有可用連接后,是否阻塞等待。True,等待;False,不等待然后報錯
                  maxusage=None,  # 一個鏈接最多被重復(fù)使用的次數(shù),None表示無限制
                  setsession=[],  # 開始會話前執(zhí)行的命令列表。如:["set datestyle to ...", "set time zone ..."]
                  ping=0,
                  # ping MySQL服務(wù)端,檢查是否服務(wù)可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always
                  host='127.0.0.1',
                  port=3306,
                  user='root',
                  password='123',
                  database='pooldb',
                  charset='utf8'
              )
      
          def __new__(cls, *args, **kwargs):
              if not hasattr(SingletonDBPool, "_instance"):
                  with SingletonDBPool._instance_lock:
                      if not hasattr(SingletonDBPool, "_instance"):
                          SingletonDBPool._instance = object.__new__(cls, *args, **kwargs)
              return SingletonDBPool._instance
      
          def connect(self):
              return self.pool.connection()

      app.py

      from pool import SingletonDBPool
      
      def run():
          pool = SingletonDBPool()
          conn = pool.connect()
          # xxxxxx
          cursor = conn.cursor()
          cursor.execute("select * from td where id=%s", [5, ])
          result = cursor.fetchall()  # 獲取數(shù)據(jù)
          cursor.close()
          conn.close()
      
      if __name__ == '__main__':
          run()

       用裝飾器實現(xiàn)的單利模式

      #
      def wrapper(cls):
          instance = {}
          def inner(*args,**kwargs):
              if cls not in  instance:
                  instance[cls] = cls(*args,**kwargs)
              return instance[cls]
          return inner
      
      @wrapper
      class Singleton(object):
          def __init__(self,name,age):
              self.name = name
              self.age = age
      
      obj1 = Singleton('haiyan',22)
      obj2 = Singleton('xx',22)
      print(obj1)
      print(obj2)

      posted on 2018-03-27 14:37  WorthWaitingFor  閱讀(587)  評論(0)    收藏  舉報

      導(dǎo)航

      主站蜘蛛池模板: 国产精品熟女乱色一区二区| 国产乱国产乱老熟300部视频 | 疏勒县| 日韩av一区二区高清不卡 | 国产亚洲精品精品精品| 蜜臀av一区二区三区在线| 国产av普通话对白国语| 被拉到野外强要好爽| 国产精品国产三级国产试看| 青青草无码免费一二三区| 久久人妻av无码中文专区| 中文字幕一区二区人妻电影| 亚洲精品日本一区二区| 国产乱码精品一区二区三| 日韩中文字幕免费在线观看 | 国产成人无码www免费视频播放| 色猫咪av在线观看| 韩国美女福利视频一区二区| 伊人久久大香线蕉aⅴ色| 男人又大又硬又粗视频| 国产精品日韩av一区二区| www久久只有这里有精品| 日本免费一区二区三区最新vr| 玩两个丰满老熟女久久网| 亚洲无人区一区二区三区| 久久99精品久久久久久| 国产精品亚洲一区二区z| 国产一区二区三区麻豆视频| 精品亚洲AⅤ无码午夜在线| 熟妇人妻无码中文字幕老熟妇| 成人性生交片无码免费看| 久久这里只精品国产免费9| 久久精品国产亚洲AV麻| 欧洲熟妇熟女久久精品综合| 别揉我奶头~嗯~啊~的视频| 日韩激情一区二区三区| 天堂va蜜桃一区二区三区| 黑人巨大videos极度另类| 九寨沟县| 亚洲日本欧美日韩中文字幕| 国产一区二区不卡在线|