[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.
$ ./t.py
<__main__.SingleFactory instance at 0x1004d1290>
<__main__.SingleFactory instance at 0x1004d1290>
1
1

Wish this helps.
regards,
Stanley Huang

Comments

Popular posts from this blog

[Level 1] Rar tool for Solaris.

[Level 2] iif in Python