Introduction to OOP Chapter 24: Design Patterns : next previous audio real text


Problem: You want to ensure that there is never more than one instace of a given class.

Solution: Make the constructor private, have a method that returns just one instance, which is held inside the class itself.

class SingletonClass {
	static SingletonClass * oneAndOnly () { return theOne; }
	static SingletonClass * theOne;
	SingletonClass () { ... }

	// static initialization
SingletonClass * SingletonClass::theOne = new SingletonClass();
Intro OOP, Chapter 24, Slide 11