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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值