Salibra

It's the best of time and it's the worst of time.

导航

Python基础篇【第6篇】: Python单例模式

Posted on 2016-02-23 18:33  salibra  阅读(125)  评论(0)    收藏  举报

单例模式

所谓单例,是指一个类的实例从始至终只能被创建一次。

根据Python类方法一段中的定义,类方法分为三种:静态方法、类方法、普通方法。前两种的所有者是类。而类在内存中只会保存一份。我们可以利用这个性质进行单利模式的开发。

#!/usr/bin/env python
# -*- coding:utf-8 -*-

#单例类
class Singleton():

    __static_instance = None                           #初始置为None
    def _init__(self,arg1,arg2....):
        //do some things

    @classmethod                                   
    def GetInstance(cls):
        if cls.__static_instance:
            return cls.__static_instance      
        else:
            cls.__static_instance = Singleton()
            return Singleton.__static_instance

def clientUI():
    obj1 = Singleton.GetInstance(arg1,arg2...)
    print id(obj1)
    obj2 = Singleton.GetInstance(arg1,arg2...)
  
print id(obj2)
  
return

if
__name__=='__main__':
  clientUI();

方法一:

如果想使得某个类从始至终最多只有一个实例,使用__new__方法会很简单。Python中类是通过__new__来创建实例的:

class Singleton(object):
    def __new__(cls,*args,**kwargs):
        if not hasattr(cls,'_inst'):
            cls._inst=super(Singleton,cls).__new__(cls,*args,**kwargs)
        return cls._inst
if __name__=='__main__':
    class A(Singleton):
        def __init__(self,s):
            self.s=s      
    a=A('apple')   
    b=A('banana')
    print id(a),a.s
    print id(b),b.s