Singleton Instance vs Class Methods

There are two different ways to implement the approach based on class methods:

  • Make a singleton instance using a class hidden from everybody, and hide its methods behind wrapper class methods with identical signatures, or
  • Make class methods that do all the work

The implications of the first implementation are that everything you can do with a singleton, you can do with the hidden singleton:

  • using a subclass becomes a possibility
  • switching the instance in the middle of the run is easy
  • the state lives in instance variables
  • initialization follows the familiar pattern

If you go for an implementation that does not use a singleton, you would be relying on static variables to keep your current state. That is a legitimate choice, but the initialization pattern becomes different (perhaps even using a dispatch_once), you cannot switch the implementation in the middle without relying on some ugly if conditions, and using a subclass becomes a lot more tricky.

Testing the first implementation is somewhat easier than testing the second one, because you can provide a separate implementation of the singleton for testing, perhaps through the back door; with a static-based implementation, this route cannot be taken.

To summarize, I would use a singleton-based solution, with the singleton optionally hidden behind a “facade” that provides access to singleton’s methods. I would not use an implementation where all state must be placed in static variables.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)