advertisement

Article:
  Using the Singleton Pattern
Subject:   Singleton Considered Harmful
Date:   2003-08-28 11:09:01
From:   jimothy
Aside from often being overused as a substitute for global variables or functions (static methods/variables or a better design should eliminate this need), a potential problem with the Singleton pattern is it makes the class determine how it will be used.


The author's example of the find dialog demonstrates my point well. While Word may only want to display one find dialog, Word (or the code that responds to the Find menu select or Ctrl-F event) should be responsible for enforcing this, not the find dialog itself. The reusability of the Find dialog is limited because its internal enforcement of the number of instances is inappropriate. The same is true of the SingletonFrame example.


While the StringManager class may be a more appropriate use of the Singleton pattern than the SingletonFrame, it too may be inappropriate. An alternative, and arguably better, solution may be the use of the Factory pattern. A StringManagerFactory can create instances of StringManager, or return a cached copy when appropriate. This is more flexible, because it allows client code, not StringManager, to determine how many StringManagers are necessary to accomplish a task, and because the Factory can return subclasses of StringManager should this ever be necessary.


Finally, to ease unit testing, it is often best to pass an instance of StringManager to the methods or classes that use the StringManager, rather than have those classes or methods get an instance from either StringManager or StringManagerFactory. The reason for this is you can pass a StringManager instance configured appropriately for your unit test, or use a mock-object subclass of StringManager.

Main Topics Oldest First

Showing messages 1 through 2 of 2.

  • Singleton Considered Harmful
    2003-08-29 05:15:05  diegof79 [Reply | View]

    I agree with your comment, for more information on why the singleton pattern is considered harmful see:

    http://www.c2.com/cgi/wiki?SingletonsAreEvil
    http://www.c2.com/cgi/wiki?AnotherJavaSingletonProblem
  • Singleton Considered Harmful
    2003-08-29 05:14:58  diegof79 [Reply | View]

    I agree with you comment, for more information on why the singleton pattern is considered harmful see:

    http://www.c2.com/cgi/wiki?SingletonsAreEvil
    http://www.c2.com/cgi/wiki?AnotherJavaSingletonProblem