GofPatterns Gofpatterns  





Design Patterns  «Prev  Next»
Lesson 8Singleton Implementation
ObjectiveWrite a Class that uses the Singleton Pattern.

Write Class that uses the Singleton Pattern

The implementation is the most language-dependent part of the pattern.
  1. Singleton Java
  2. Singleton C++
The trick to the Singleton is threefold:
  1. A nonpublic constructor so that arbitrary instances of the class can not be created.
  2. A field that holds a single unique instance of the class.
  3. A method that returns a reference (Java) or a pointer (C++) to the field.


The Singleton pattern is an easy to understand design pattern. Sometimes, there may be a need to have one and only one instance of a given class during the lifetime of an application. This may be due to necessity or due to the fact that only a single instance of the class is sufficient. For example, we may need a single database connection object in an application. The Singleton pattern is useful in such cases because it ensures that there exists one and only one instance of a particular object ever. Furthermore, it suggests that client objects should be able to access the single instance in a consistent manner.

Singleton Pattern - Exercise

Click on the link below to perform the
Singleton Pattern - Exercise