|Lesson 8||Singleton Implementation|
|Objective||Write 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.
The trick to the Singleton is threefold:
A nonpublic constructor so that arbitrary instances of the class can not be created.
A field that holds a single unique instance of the class.
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