Tuesday, May 22, 2007


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

No comments: