GofPatterns GofPatterns

Designing Software  «Prev 

Singleton Pattern versus Dialogs Pattern Comparison

Lessons learned from Design Patterns

Actually, if creating new dialogs is expensive, but changing the message they display is not, you might indeed want to use the Singleton pattern here.
You might need to modify it if it is possible for two different dialogs to be displayed simultaneously.
With the Singleton design pattern you can:
  1. Ensure that only one instance of a class is created
  2. Provide a global point of access to the object
  3. Allow multiple instances in the future without affecting a singleton class's clients
Ensure a class has only one instance, and provide a global point of access to it.
The figure below illustrates the Singleton design pattern class diagram.

Singleton Design Pattern
As you can see from the figure above, the Singleton design pattern is relatively simple. Singletons maintain a static reference to the sole singleton instance and return a reference to that instance from a static instance() method.
Example 1 shows a classic Singleton design pattern implementation:

Example 1. The classic singleton

public class ClassicSingleton {
   private static ClassicSingleton instance = null;
   protected ClassicSingleton() {
      // Exists only to defeat instantiation.
   public static ClassicSingleton getInstance() {
      if(instance == null) {
         instance = new ClassicSingleton();
      return instance;