Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should you use the singleton pattern instead of a static class? [closed]

Name the design considerations in deciding between use of a singleton versus a static class. In doing this, you're kind of forced to contrast the two, so whatever contrasts you can come up with are also useful in showing your thought process! Also, every interviewer likes to see illustrative examples. :)

like image 229
cdleary Avatar asked Sep 05 '08 18:09

cdleary


People also ask

Why use a singleton instead of a static class?

A Singleton can implement interfaces, inherit from other classes and allow inheritance. While a static class cannot inherit their instance members. So Singleton is more flexible than static classes and can maintain state. A Singleton can be initialized lazily or asynchronously and loaded automatically by the .

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).

When should singleton pattern be used?

Use the Singleton pattern when a class in your program should have just a single instance available to all clients; for example, a single database object shared by different parts of the program. The Singleton pattern disables all other means of creating objects of a class except for the special creation method.


2 Answers

  • Singletons can implement interfaces and inherit from other classes.
  • Singletons can be lazy loaded. Only when it is actually needed. That's very handy if the initialisation includes expensive resource loading or database connections.
  • Singletons offer an actual object.
  • Singletons can be extended into a factory. The object management behind the scenes is abstract so it's better maintainable and results in better code.
like image 92
Tobias Avatar answered Oct 05 '22 07:10

Tobias


How about "avoid both"? Singletons and static classes:

  • May introduce global state
  • Get tightly coupled to multiple other classes
  • Hide dependencies
  • Can make unit testing classes in isolation difficult

Instead, look into Dependency Injection and Inversion of Control Container libraries. Several of the IoC libraries will handle lifetime management for you.

(As always, there are exceptions, such as static math classes and C# extension methods.)

like image 45
TrueWill Avatar answered Oct 05 '22 08:10

TrueWill