Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use a singleton instead of static methods?

I have never found good answers to these simple questions about helper/utility classes:

  • Why would I create a singleton (stateless) instead of using static methods?
  • Why would an object instance be needed if an object has no state?
like image 348
Sebastien Lorber Avatar asked May 04 '10 12:05

Sebastien Lorber


People also ask

What is the reason to use a singleton instead of a class with only static members and never instantiate any object of that class?

The Singleton pattern has several advantages over static classes. First, a singleton can extend classes and implement interfaces, while a static class cannot (it can extend classes, but it does not inherit their instance members).

Why would you want a singleton?

A singleton should be used when managing access to a resource which is shared by the entire application, and it would be destructive to potentially have multiple instances of the same class. Making sure that access to shared resources thread safe is one very good example of where this kind of pattern can be vital.

Should all singleton methods be static?

A singleton doesn't use static methods, so you won't have trouble using it in a non-static context. Singletons can be extended/subclassed. Since they're objects, they can be injected into other objects, which allow for the creation of some great design patterns utilizing the concepts of dependency injection.


1 Answers

Often, singletons are used to introduce some kind of global state to an application. (More often than really necessary, to be honest, but that's a topic for another time.)

However, there are a few corner cases where even a stateless singleton can be useful:

  • You expect to extend it with state in the foreseeable future.
  • You need an object instance for some particular technical reason.
    Example: Synchonization objects for the C# lock or the Java synchronized statement.
  • You need inheritance, i.e., you want to be able to easily replace your singleton with another one using the same interface but a different implementation.
    Example: The Toolkit.getDefaultToolkit() method in Java will return a singleton whose exact type is system dependent.
  • You want reference equality for a sentinel value.
    Example: DBNull.Value in C#.
like image 142
Heinzi Avatar answered Oct 21 '22 01:10

Heinzi