[ Level 2 ] Test Singleton Implementation in Python.

Days ago, just search how to use implement "Singleton" design pattern. (http://stackoverflow.com/questions/6760685/crea(ing-a-singleton-in-python) And today, I just need to implement for it. In my case, I need to create mutliple loggers and I also want to use "Singleton" to reduce system resource usage. Therefore, I create a Singleton meta class and also use a parameter called "singleton_id" to define the instance category. Source Code:
#!/bin/env python
class Singleton(object):
    _singleton_key = 'singleton_id'
    _instance = {}
    def __new__(class_, *args, **kwargs):
        if class_._singleton_key not in kwargs.keys():
            kwargs[class_._singleton_key] = ''
        if class_._singleton_key in kwargs and kwargs[class_._singleton_key] not in class_._instance.keys():
            class_._instance[kwargs[class_._singleton_key]] = object.__new__(class_)
        return class_._instance[kwargs[class_._singleton_key]]

class mySingleton(Singleton):
    def __init__(self, name, singleton_id=None):
        self.name = name
        pass

a0 = mySingleton('a')
print a0
print a0.name

a1 = mySingleton('a', singleton_id='a')
print a1
print a1.name

a2 = mySingleton('a', singleton_id='a')
print a2
print a2.name

a3 = mySingleton('b', singleton_id='a')
print a3
print a3.name

a4 = mySingleton('b', singleton_id='a')
print a4
print a4.name

print '----'
print a0
print a0.name
print a1
print a1.name
print a2
print a2.name
Output:
<__main__.mySingleton object at 0x7f2248065f10>
a
<__main__.mySingleton object at 0x7f2248065f50>
a
<__main__.mySingleton object at 0x7f2248065f50>
a
<__main__.mySingleton object at 0x7f2248065f50>
b
<__main__.mySingleton object at 0x7f2248065f50>
b
----
<__main__.mySingleton object at 0x7f2248065f10>
a
<__main__.mySingleton object at 0x7f2248065f50>
b
<__main__.mySingleton object at 0x7f2248065f50>
b

Wish this helps.

regards,
Stanley Huang

Comments

Popular posts from this blog

[Level 2] Shell Interactive With Zenity Episode 5 -- list

[Level 2] iif in Python