Wednesday, March 9, 2011

[Level 3] Design Pattern in Python(1): Singleton

If you want to implement singleton in Python,
you can refer the  following sample code.

#!/usr/bin/env python
class SingleFactory:
    __single = None
    def __init__( self ):
        if not SingleFactory.__single:
            SingleFactory.__single = self
    def getInstance( self ):
        return SingleFactory.__single

if __name__ == '__main__':
    f = SingleFactory()
    a = f.getInstance()
    b = f.getInstance()
    print a
    print b
    a.count = 1
    print a.count
    print b.count

Execute it.
$ ./
<__main__.SingleFactory instance at 0x1004d1290>
<__main__.SingleFactory instance at 0x1004d1290>

Wish this helps.
Stanley Huang