locked
When to use singleton-pattern RRS feed

  • Question

  • Hi!

    Are there any when to and when not to use Singleton pattern?

    F.ex. If there is a method that will be called verry frequently there is a big chance of a que with waiting calls on that method, while the first call is executing.

    //Daniel

    Tuesday, March 20, 2007 8:13 AM

All replies

  • Hi Daniel,

    Singleton pattern is generally used to service instance independent or static data where multiple threads can access data at same time. One example can be state codes.

    http://DotNetWithMe.blogspot.com
    vikas goyal

    Tuesday, March 20, 2007 8:55 AM
  • Hi Daniel,

    The objective of the Singleton pattern as defined in Design Patterns is to "ensure a class has only one instance, and provide a global point of access to it". 

    For example, a class could be used to maintain an global counter, keeping track of an integer value that is being used in multiple classes of your application. Also, the class needs to be able to increment and return the current value of the counter. In this situation, the desired class behavior would be to have exactly one instance of the class that maintains the integer and nothing more.

    You could be tempted to use a static variable to solve the problem. But this really solves half the problem, the global accessibility, but does not ensure that there is only one instance of the class running at any given time.

    The class should be responsible of  letting only one instance of the class itself and not the user of the class. The users of the class should always be free from having to monitor and control the number of running instances of the class.

    So, as far as you keep two objectives, you should don't have problem using a singleton.

    You can find more information here ....

    http://www-128.ibm.com/developerworks/webservices/library/co-single.html

    Regards
                              viraxo




    Tuesday, March 20, 2007 1:28 PM
  • The short answer is almost  never

    The long answer is that Singletons are basically a nice OO way to introduce "global variables"  and it has several bad side effects like tight coupling by all the class users etc. (see http://blogs.msdn.com/scottdensmore/archive/2004/05/25/140827.aspx)

    It is better to use alternative ways to create single instances

     

    Arnon

    Thursday, March 22, 2007 8:51 PM