CSC/ECE 517 Fall 2010/ch3 3f DF: Difference between revisions
Jump to navigation
Jump to search
Line 4: | Line 4: | ||
== Introduction == | == Introduction == | ||
The Singleton design pattern ensures that there is no more than one instance of an object in existence at a time. This is accomplished by protecting the allocation and deallaction methods of the class to restrict them from general use. Instead of calling these methods directly, all requests for the object are routed through a public interface which only creates the object if it doesn't exist already. Upon creation, the object is stored in a class variable and this single instance is also returned to all future callers. | |||
UML Diagram | UML Diagram | ||
== Usage == | |||
== Static Language Implementation == | == Static Language Implementation == |
Revision as of 04:50, 5 October 2010
The Singleton pattern in static and dynamic languages
Introduction
The Singleton design pattern ensures that there is no more than one instance of an object in existence at a time. This is accomplished by protecting the allocation and deallaction methods of the class to restrict them from general use. Instead of calling these methods directly, all requests for the object are routed through a public interface which only creates the object if it doesn't exist already. Upon creation, the object is stored in a class variable and this single instance is also returned to all future callers.
UML Diagram
Usage
Static Language Implementation
C++
class MySingleton { public: static MySingleton* Instance() { if(s_pSingletonObject == NULL) s_pSingletonObject = new MySingleton; return s_pSingletonObject; } static void Destroy() { if(s_pSingletonObject != NULL) { delete s_pSingletonObject; s_pSingletonObject = NULL; } } //Begin interface functions //... //End interface functions private: //Direct access to the constructor/destructor is prohibited MySingleton() {} virtual ~MySingleton() {} static MySingleton* s_pSingletonObject; }; MySingleton::s_pSingletonObject = NULL;
Dynamic Language Implementation
Ruby
Implementation
Singleton pattern source code
Usage
class MySingleton include Singleton # Begin interface methods # ... # End interface methods end