Entry
Singleton pattern
Jul 5th, 2000 10:03
Nathan Wallace, Hans Nowak, Snippet 315, Magnus L. Hetland
"""
Packages: oop
"""
"""
> I can't seem to figure out how to implement the singleton pattern in
> Python however. It is one of my favorite patterns and I use it
> constantly.
>
> Anybody have any pointers on how to do it?
>
>
> A short summary of the singleton pattern:
>
> Used when one and only one instance of the object is needed in your app.
> In C++ or java, you hide the constructor as protected (not important).
> The instance is accessed through a static function (typically
> instance()). The first time instance is called, it initializes the
> object with a constructor.
If you don't insist on using this exact implementation, I think you
can do this quite easily with a factory function (looking like a class to
the user... :)
"""
class _Hello:
instance = None
def __init__(self):
self.subject = "world"
def setSubject(self,subject):
self.subject = subject
def hello(self):
print "Hello,", self.subject
def Hello():
if _Hello.instance == None:
_Hello.instance = _Hello()
return _Hello.instance
# This would work like this:
x = Hello()
y = Hello()
x.hello()
# Hello, world
x.setSubject("web")
y.hello()
# Hello, web
"""
This is what you want, isn't it? The class _Hello wouldn't be exported
from a module, so the factory Hello is all the users will see.
"""