Using a factory to overcome the shortcomings of a Singleton

Singletons are not as much a pattern as they used to be.


The reasons for their low popularity seem to be:
  • They break the single responsibility principle
  • They tightly couple classes where they shouldn't
However, the reasons we want to use them are still popular.  We often want a single point of control to control access to things such as databases, and other resources. How exactly does one not use a singleton when a single instance of a class is required?

The most obvious way around this, whilst addressing the problems caused by a singleton is a factory class.

Imagine that I wish to control access to my database.  Instead of using a data singleton class one could link into the home class to an IData instance which breaks the tight coupling.



The above factory class solves the problem of violation of the single responsibility principle.  It is this class which maintains the single instance of the data. The data class is now free to only worry about handling its data, and not how many of it there are.

As for unit testing, one can simply make ones own mock which derives from IData, and replace the module's data with the mock created.

Comments

Popular Posts