Singleton

Ensures a class has only one instance and provides a global point of access to it. Use it when there must be exactly one instance of a class accessible from a well-known access point, or when the sole instance should be extensible by subclassing and clients should be able to use an extended instance without modifying their code.

Examples:

  • A country can have only one official government regardless of who forms it. Similarly, a Singleton class makes its constructor private and exposes only a static getInstance() method that always returns the same cached object — much like 'The Government of X' is always a single entity regardless of who accesses it.
class MazeFactory {
public:
  static MazeFactory* Instance();
  // ... factory operations ...
protected:
  MazeFactory() {}
private:
  static MazeFactory* _instance;
};
MazeFactory* MazeFactory::_instance = nullptr;
MazeFactory* MazeFactory::Instance() {
  if (!_instance) _instance = new MazeFactory;
  return _instance;
}