Faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

2 of 2 people (100%) answered Yes
Recently 1 of 1 people (100%) answered Yes

Entry

Singleton pattern

Sep 15th, 2009 02:19
jick heir, Nathan Wallace, Hans Nowak, Snippet 314, Chris Tavares


"""
Packages: oop
"""
"""
> I have recently become a Python convert and am enjoying myself
> immensely. Kudo's to Guido!.
>
> 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.
Use a module level function, along with a global variable. Something like
this:
"""
# foo.py:
_fooInstance = None
class _fooClass:
    pass
def FooInstance():
    global _fooInstance
    if _fooInstance is None:
        _fooInstance = _fooClass()
    return _fooInstance
"""
Users would call foo.FooInstance() to get the singleton object.
"""
http://sundhedernaeringguide.blogspot.com/
http://zdravevyzivypruvodce.blogspot.com/
http://guidasalutenutrizione.blogspot.com/
http://gesundheiternahrungpflege.blogspot.com/
http://soinssantenutrition.blogspot.com/
http://zdravljeprehranavodic.blogspot.com/
http://healthnutritionhoito.blogspot.com/
http://hlhnutgr.blogspot.com/
http://gezondheidvoedinggids.blogspot.com/
http://taplalkozas-egeszsegugyikezikonyv.blogspot.com/
http://hlthnutbg.blogspot.com/