I just finished rereading Design Patterns: Elements of Reusable Object-Oriented Software. As a little experiment, I will explore how far I can get with the book’s fundamental design patterns with Python, an object-oriented scripting language that I am trying to pick up.
One of the first design patterns I came across even before reading DP is the Singleton pattern. The basic Singleton pattern creates a single instance for an entire system to use. A system task scheduler or print spool are examples of singletons.
The source code of my implementation of the Singleton pattern in Python is presented here:
# Singleton class definition class MySingleton ( object ): __instance = None def __new__( cname ): if not cname.__instance: cname.__instance = super( MySingleton, cname ).__new__( cname ) return cname.__instance def setX( self, x ): self.x = x def getX( self ): return self.x # Singleton client code a = MySingleton() b = MySingleton() print a print b a.setX("hello") print b.getX()
The output from the Python interpreter is:
<__main__.MySingleton object at 0xb7ebb24c> <__main__.MySingleton object at 0xb7ebb24c> hello
Printing the objects shows that the objects are located at the same address and are the same type. Furthermore, invoking operations that modify the instance that is attached to “a” affects the one that is attached to “b.” Changes to “a” are reflected in “b.” In other words, the instance of MySingleton that is referenced by “a” and “b” are the same. This demonstrates the Singleton pattern in Python.