13.4k views
1 vote
How could one implement a Singleton design pattern

A) Declare a class with a private constructor and a static method to get the instance
B) Use a global variable to store the single instance
C) Implement a public constructor with a check for existing instances
D) Make all members of the class static

User Jengar
by
8.3k points

1 Answer

4 votes

Final answer:

To implement a Singleton pattern, a class with a private constructor and a static method to get the instance is used. This ensures only one instance of the class exists. Options B, C, and D do not correctly implement the Singleton pattern.

Step-by-step explanation:

To implement a Singleton design pattern, option A is typically the correct approach, where you:

  1. Declare a class with a private constructor.
  2. Provide a static method within the class that returns the instance of the class. This method is often called getInstance().

When the

getInstance()

method is called, it either creates a new instance if one doesn't already exist, or returns the one that was previously created. This pattern ensures that there is only one instance of the class in the application.

Option B, using a global variable, is not a standard implementation of the Singleton pattern because it doesn't enforce the single instance rule within the class's structure and relies on the global scope.

Option C is incorrect since a public constructor defeats the purpose of the Singleton pattern, which is to control the instantiation of the class internally.

Lastly, option D, making all members of the class static would not enforce the Singleton pattern, since this approach does not control the instantiation to just one object; it simply provides global access to methods and properties.

User Ebin Joy
by
8.3k points