2.6. The Singleton Pattern

The GOF book defines the intent of the singleton pattern as being to ensure that a class has only one instance and that global access is provided to that single instance.

Singletons are generally used in situations where data needs to be kept synchronized or for centralizing shared resources.

Take for example the situation in which two views display and allow the user to update data, but hold two separate instances of that data. When one view updates the data, the other view will be out of sync. However, if both views are pointing to the same object, this problem no longer exists; all you have to do is refresh the views (which you would probably do by implementing the observer pattern on the model with the views as observers).

Another possibility is two views that need to access the same external data source via a service call. If each view has its own instance of the service call, you now have to maintain that code in two different locations and you will be creating duplicate resources (in the form of objects) that do essentially the same thing. Again, this is not an issue if both views are referencing the same object.

A typical singleton class is made up of three major parts. These are:

  • A static variable that holds a reference to the single instance.

  • A public static method (most commonly called getInstance) that provides global access to the stored instance if one already exists and creates it if it does not.

  • Some means of limiting the class to a single ...

Get Professional Cairngorm™ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.