Exercise objective: Write a Panda class that applies the Singleton pattern (exactly one instance, globally accessible through a controlled access point).
No submission was received. Please go back to the exercise page and click Submit.
private (or at least non-public) so callers cannot do new Panda().static field).getInstance() (Java/C#) or instance() (common in C++ examples).getInstance() concurrently.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.");
}
}
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;
};
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.