• 技术文章 >Python技术 >Python基础教程

    python单例模式是什么意思

    爱喝马黛茶的安东尼爱喝马黛茶的安东尼2019-10-29 17:32:30原创2900

    单例模式(Singleton Pattern)是一种常用的软件设计模式,该模式的主要目的是确保某一个类只有一个实例存在。当你希望在整个系统中,某个类只能出现一个实例时,单例对象就能派上用场。

    单例模式

    a、单例模式分为四种:文件,类,基于__new__方法实现单例模式,基于metaclass方式实现。

    b、类实现如下:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    class Sigletion(objects):

      import time

      def __init__(self):

        time.sleep(1)

      @classmethod

      def instance(cls,*args,**kwargs)

        if not hasattr(Sigletion,'_instance'):

          Sigletion._instance=Sigletion(*args,**kwargs)

        return Sigletion._instance

      

    import threading

      

    daf task(arg):

      obj=Sigletion.instance()

      print(obj)

      

    for i in range(10):

      t=threading.Thread(target=task,args=[i,])

      t.start()

    相关推荐:《Python免费入门教程

    c、基于__new__方法实现单例模式

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    import time

    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"):

              Singleton._instance=object.__new__(cls,*args,**kwargs)

        return Singleton._instance

      

    obj1=Singleton()

    obj2=Singleton()

    print(obj1,obj2)

      

    def task(arg):

      obj = Singleton()

      print(obj)

      

    for i in range(10):

      t = threading.Thread(target=task,args=[i,])

      t.start()

    d、基于metaclass方式实现单例模式

    1、对象是类创建,创建对象时候类的__init__方法自动执行,对象()执行类的 __call__ 方法。

    2、类是type创建,创建类时候type的__init__方法自动执行,类() 执行type的 __call__方法(类的__new__方法,类的__init__方法)。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    # 第0步: 执行type的 __init__ 方法【类是type的对象】

    class Foo:

      def __init__(self):

        pass

      

      def __call__(self, *args, **kwargs):

        pass

      

    # 第1步: 执行type的 __call__ 方法

    #    1.1 调用 Foo类(是type的对象)的 __new__方法,用于创建对象。

    #    1.2 调用 Foo类(是type的对象)的 __init__方法,用于对对象初始化。

    obj = Foo()

    # 第2步:执行Foodef __call__ 方法

    obj()

    """

      

    import threading

      

    class SingletonType(type):

      _instace_lock=threading.Lock()

      def __call__(cls, *args, **kwargs):

        if not hasattr(cls, "_instance"):

          with SingletonType._instace_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)

    专题推荐:python 单例模式
    上一篇:python如何创建类 下一篇:python如何实现多态

    相关文章推荐

    • Python中如何使用_new_实现单例模式

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网