Difference between revisions of "Singleton"

From CDOT Wiki
Jump to: navigation, search
 
Line 3: Line 3:
  
 
==Implementation==
 
==Implementation==
**Singleton pattern is implemented by creating a class with a method that creates a new instance of the object if one does not exist.
+
 
**If an instance already exists, it simply returns a reference to that object.
+
*Singleton pattern is implemented by creating a class with a method that creates a new instance of the object if one does not exist.
**To make sure that the object cannot be instantiated any other way, the constructor is made either private or protected.
+
*If an instance already exists, it simply returns a reference to that object.
 +
*To make sure that the object cannot be instantiated any other way, the constructor is made either private or protected.

Revision as of 18:54, 8 March 2007

Introduction

Singleton pattern Ensure a class only has one instance, and provide a global point of access to it. This is useful when exactly one object is needed to coordinate actions across the system.

Implementation

  • Singleton pattern is implemented by creating a class with a method that creates a new instance of the object if one does not exist.
  • If an instance already exists, it simply returns a reference to that object.
  • To make sure that the object cannot be instantiated any other way, the constructor is made either private or protected.