Design Patterns «Prev Next»

Singleton Pattern Exercise Result

Exercise objective: Write a Panda class that applies the Singleton pattern (exactly one instance, globally accessible through a controlled access point).

Your submission

No submission was received. Please go back to the exercise page and click Submit.


How to check your solution

  1. Non-public constructor: The constructor should be private (or at least non-public) so callers cannot do new Panda().
  2. Single stored instance: The class should store exactly one instance (for example, a static field).
  3. Single access point: Clients should obtain the instance via a method such as getInstance() (Java/C#) or instance() (common in C++ examples).
  4. Same object every time: Repeated calls return the same object (same reference/pointer).
  5. Optional (recommended): Thread-safety if multiple threads could call getInstance() concurrently.

Reference solution (Java)

This version uses eager initialization: the instance is created when the class is loaded. It is simple and naturally thread-safe in Java due to class initialization semantics.

public final class Panda {

  // Single instance (created once at class load time)
  private static final Panda INSTANCE = new Panda();

  // Non-public constructor prevents external instantiation
  private Panda() { }

  // Global access point
  public static Panda getInstance() {
    return INSTANCE;
  }

  // Example instance method
  public void eatBamboo() {
    System.out.println("Panda is eating bamboo.");
  }
}

Reference solution (C++)

This version uses the Meyers Singleton approach (function-local static). In C++11 and later, initialization of function-local statics is thread-safe.

#include <iostream>

class Panda {
public:
  static Panda& instance() {
    static Panda inst; // created once, thread-safe in C++11+
    return inst;
  }

  void eatBamboo() {
    std::cout << "Panda is eating bamboo." << std::endl;
  }

  Panda(const Panda&) = delete;
  Panda& operator=(const Panda&) = delete;

private:
  Panda() = default;
};

Key takeaway

A Singleton is not “a class with static methods.” The defining property is: exactly one instance plus a controlled access point. The class name does not need to include the word “Singleton”—your Panda class is the Singleton.