python中实现Single模式

#!/usr/bin/env python

#-*- coding:utf-8 -*-

 

class Singleton:

       """ A python singleton """

 

       class __impl:

              """ Implementation of the singleton interface """

 

       def spam(self):

              """ Test method, return singleton id """

              return id(Singleton.__instance)

 

       # storage for the instance reference

       __instance = None

 

       def __init__(self):

              """ Create singleton instance """

              # Check whether we already have an instance

              if Singleton.__instance is None:

                     # Create and remember instance

                     Singleton.__instance = Singleton.__impl()

              # Store instance reference as the only member in the handle

              self.__dict__['_Singleton__instance'] = Singleton.__instance

 

       def __getattr__(self, attr):

              """ Delegate access to implementation """

              return getattr(self.__instance, attr)

 

       def __setattr__(self, attr, value):

              """ Delegate access to implementation """

              return setattr(self.__instance, attr, value)

 

class SingletonType(type):

       """Singleton Metaclass"""

 

       def __init__(cls, name, bases, dic):

              super(SingletonType, cls).__init__(name, bases, dic)

              cls.instance = None

 

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

              if cls.instance is None:

                     cls.instance = super(SingletonType, cls).__call__(*args, **kwargs)

              return cls.instance

      

class MyClass:

       __metaclass__ = SingletonType

      

 

if __name__ == '__main__':

       #print dir(MyClass)

       ob1 = MyClass()

       ob2 = MyClass()

       print id(ob1), id(ob2)

      

       #print dir(Singleton)

       s1 = Singleton()

       s2 = Singleton()

       print id(s1), s1.spam()

       print id(s2), s2.spam()

阅读更多
个人分类: 软件技术
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭