Singleton Pattern   «Prev  Next»

Singleton Pattern - Exercise Result

Using the Singleton Pattern


You entered:


What are the characteristics of the Panda Class?
The Panda class can be written by simply changing a few names in one of the two implementations in the lesson.

Java Code C++ Code

Here is the Java version:
public class Panda {
 static Panda thePanda = new Panda ();
 protected Panda () {
 }
 public static Panda getThePanda() {
  return thePanda;
 }
}

Here's the C++ version:
class Panda {
  public:
    static Panda* getThePanda(){
       if (thePanda == 0) {
           thePanda = new Panda;
        }
          return thePanda;
   };
  protected:
    Panda(){};
  private:
    static Panda* thePanda;
};
Panda* Panda::thePanda = 0;
Notice that the word "Singleton" no longer appears in the class.

Java Implementation of Singleton Design Pattern

The Singleton design pattern is a well-established pattern used to ensure that a class has only one instance and provides a global point to access it. Below is a Java implementation of a Singleton class that adheres to the three essential elements: a private constructor, a static field containing the single instance, and a static factory method for obtaining the instance.
public class Singleton {
    // Step 2: Static field containing the single instance of the class
    private static final Singleton instance = new Singleton();

    // Step 1: Private constructor to prevent instantiation from other classes
    private Singleton() {
        // Initialization code can be placed here
    }

    // Step 3: Static factory method for obtaining the single instance
    public static Singleton getInstance() {
        return instance;
    }

    // Additional methods to perform Singleton-specific logic can be added here
}

Explanation of Singleton Components

  1. Private Constructor: The constructor is marked as `private` to ensure that no other class can instantiate a `Singleton` object. Any initialization logic for the Singleton can be placed within this constructor.
  2. Static Field: The `instance` field is `static` and `final`, ensuring that only one instance of the `Singleton` class exists. The instance is created at the time of class loading, making this an eager initialization approach.
  3. Static Factory Method: The `getInstance()` method is a public `static` method that returns the single `instance` of the `Singleton` class. This method serves as the global point for obtaining the instance.

This implementation uses eager initialization, which means the Singleton instance is created when the class is loaded. This approach is thread-safe but may not be suitable for all scenarios, especially if the Singleton class is resource-intensive to instantiate. By adhering to these three essential elements, this Java implementation ensures that the Singleton class maintains a single instance throughout the application, thereby aligning with the core principles of the Singleton design pattern.