Conventions/code/patterns/singleton

From Woozle Writes Code
Jump to navigation Jump to search

Singleton objects are a fairly common code-pattern; the following are my conventions for them.

The basic idea of a singleton class is that you want to only ever create one object from it.

Since much of the usefulness of this method is the ability to have methods that are effectively global functions while still being nicely packaged in a way that makes it clear where they come from (and allows autoloading), it's useful for the class to have a static method (I use "Me()") that references the singleton object.

  • The "Me()" method can either:
    • A. construct the singleton object the first time it is called
      • This only works if we can be sure it will first be called by code which knows the proper class to invoke, i.e. application (rather than library) code.
    • B. expect that the class constructor will set the singleton (the singleton object must be explicitly created outside the class)

The class's constructor can also include a check to make sure it has not already been instantiated, and throw a hissy if that happens.