关闭

python中实现Single模式

680人阅读 评论(0) 收藏 举报

#!/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()

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:11764次
    • 积分:231
    • 等级:
    • 排名:千里之外
    • 原创:11篇
    • 转载:1篇
    • 译文:0篇
    • 评论:0条
    文章分类