What real (i.e. practical) difference exists between a static class and a singleton pattern?
Both can be invoked without instantiation, both provide only one "Instance" and neither of them is thread-safe. Is there any other difference?
What makes you say that either a singleton or a static method isn't thread-safe? Usually both should be implemented to be thread-safe.
The big difference between a singleton and a bunch of static methods is that singletons can implement interfaces (or derive from useful base classes, although that's less common, in my experience), so you can pass around the singleton as if it were "just another" implementation.
The true answer is by Jon Skeet, on another forum here.
A singleton allows access to a single created instance - that instance (or rather, a reference to that instance) can be passed as a parameter to other methods, and treated as a normal object.
A static class allows only static methods.
interface
with a Singleton class, but a class's static methods (or e.g. a C# static class
) cannot.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). A singleton can be initialized lazily or asynchronously while a static class is generally initialized when it is first loaded, leading to potential class loader issues. However the most important advantage, though, is that singletons can be handled polymorphically without forcing their users to assume that there is only one instance.
static
classes are not for anything that needs state. It is useful for putting a bunch of functions together i.e Math
(or Utils
in projects). So the class name just gives us a clue where we can find the functions and nothing more.
Singleton
is my favorite pattern and I use it to manage something at a single point. It's more flexible than static
classes and can maintain it's state. It can implement interfaces, inherit from other classes and allow inheritance.
My rule for choosing between static
and singleton
:
If there is a bunch of functions that should be kept together, then static
is the choice.
Anything else which needs single access to some resources, could be implemented as a singleton
.
Static Class:-
You cannot create the instance of static class.
Loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.
Static Class cannot have constructor.
We cannot pass the static class to method.
We cannot inherit Static class to another Static class in C#.
A class having all static methods.
Better performance (static methods are bonded on compile time)
Singleton:-
You can create one instance of the object and reuse it.
Singleton instance is created for the first time when the user requested.
Singleton class can have constructor.
You can create the object of singleton class and pass it to method.
Singleton class does not say any restriction of Inheritance.
We can dispose the objects of a singleton class but not of static class.
Methods can be overridden.
Can be lazy loaded when need (static classes are always loaded).
We can implement interface(static class can not implement interface).
A static class is one that has only static methods, for which a better word would be "functions". The design style embodied in a static class is purely procedural.
Singleton, on the other hand, is a pattern specific to OO design. It is an instance of an object (with all the possibilities inherent in that, such as polymorphism), with a creation procedure that ensures that there is only ever one instance of that particular role over its entire lifetime.
To expand on Jon Skeet's Answer
The big difference between a singleton and a bunch of static methods is that singletons can implement interfaces (or derive from useful base classes, although that's less common IME), so you can pass around the singleton as if it were "just another" implementation.
Singletons are easier to work with when unit testing a class. Wherever you pass singletons as a parameter (constructors, setters or methods) you can instead substitute a mocked or stubbed version of the singleton.
Here's a good article: http://javarevisited.blogspot.com.au/2013/03/difference-between-singleton-pattern-vs-static-class-java.html
can't override methods, but can use method hiding. (What is method hiding in Java? Even the JavaDoc explanation is confusing)
public class Animal {
public static void foo() {
System.out.println("Animal");
}
}
public class Cat extends Animal {
public static void foo() { // hides Animal.foo()
System.out.println("Cat");
}
}
In summary, I would only use static classes for holding util methods, and using Singleton for everything else.
Edits
static classes are lazy loaded as well. Thanks @jmoreno (When does static class initialization happen?)
method hiding for static classes. Thanks @MaxPeng.
I'm not a great OO theorist, but from what I know, I think the only OO feature that static classes lack compared to Singletons is polymorphism. But if you don't need it, with a static class you can of course have inheritance ( not sure about interface implementation ) and data and function encapsulation.
The comment of Morendil, "The design style embodied in a static class is purely procedural" I may be wrong, but I disagree. In static methods you can access static members, which would be exactly the same as singleton methods accessing their single instance members.
edit:
I'm actually thinking now that another difference is that a Static class is instantiated at program start* and lives throughout the whole life span of the program, while a singleton is explicitly instantiated at some point and can be destroyed also.
* or it may be instantiated at first use, depending on the language, I think.
To illustrate Jon's point what's shown below cannot be done if Logger was a static class.The class SomeClass
expects an instance of ILogger
implementation to be passed into its constructor.
Singleton class is important for dependency injection to be possible.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var someClass = new SomeClass(Logger.GetLogger());
}
}
public class SomeClass
{
public SomeClass(ILogger MyLogger)
{
}
}
public class Logger : ILogger
{
private static Logger _logger;
private Logger() { }
public static Logger GetLogger()
{
if (_logger==null)
{
_logger = new Logger();
}
return _logger;
}
public void Log()
{
}
}
public interface ILogger
{
void Log();
}
}
Well a singleton is just a normal class that IS instantiated but just once and indirectly from the client code. Static class is not instantiated. As far as I know static methods (static class must have static methods) are faster than non-static.
Edit:
FxCop Performance rule description:
"Methods which do not access instance data or call instance methods can be marked as static (Shared in VB). After doing so, the compiler will emit non-virtual call sites to these members which will prevent a check at runtime for each call that insures the current object pointer is non-null. This can result in a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue."
I don't actually know if this applies also to static methods in static classes.
Main differences are:
Singleton is better approach from testing perspective. Unlike static classes , singleton could implement interfaces and you can use mock instance and inject them.
In the example below I will illustrate this. Suppose you have a method isGoodPrice() which uses a method getPrice() and you implement getPrice() as a method in a singleton.
singleton that’s provide getPrice functionality:
public class SupportedVersionSingelton {
private static ICalculator instance = null;
private SupportedVersionSingelton(){
}
public static ICalculator getInstance(){
if(instance == null){
instance = new SupportedVersionSingelton();
}
return instance;
}
@Override
public int getPrice() {
// calculate price logic here
return 0;
}
}
Use of getPrice:
public class Advisor {
public boolean isGoodDeal(){
boolean isGoodDeal = false;
ICalculator supportedVersion = SupportedVersionSingelton.getInstance();
int price = supportedVersion.getPrice();
// logic to determine if price is a good deal.
if(price < 5){
isGoodDeal = true;
}
return isGoodDeal;
}
}
In case you would like to test the method isGoodPrice , with mocking the getPrice() method you could do it by:
Make your singleton implement an interface and inject it.
public interface ICalculator {
int getPrice();
}
Final Singleton implementation:
public class SupportedVersionSingelton implements ICalculator {
private static ICalculator instance = null;
private SupportedVersionSingelton(){
}
public static ICalculator getInstance(){
if(instance == null){
instance = new SupportedVersionSingelton();
}
return instance;
}
@Override
public int getPrice() {
return 0;
}
// for testing purpose
public static void setInstance(ICalculator mockObject){
if(instance != null ){
instance = mockObject;
}
test class:
public class TestCalculation {
class SupportedVersionDouble implements ICalculator{
@Override
public int getPrice() {
return 1;
}
}
@Before
public void setUp() throws Exception {
ICalculator supportedVersionDouble = new SupportedVersionDouble();
SupportedVersionSingelton.setInstance(supportedVersionDouble);
}
@Test
public void test() {
Advisor advidor = new Advisor();
boolean isGoodDeal = advidor.isGoodDeal();
Assert.assertEquals(isGoodDeal, true);
}
}
In case we take the alternative of using static method for implementing getPrice() , it was difficult to the mock getPrice(). You could mock static with power mock, yet not all product could use it.
JDK has examples of both singleton and static, on the one hand java.lang.Math
is a final class with static methods, on the other hand java.lang.Runtime
is a singleton class.
Advantages of singleton
If your need to maintain state than singleton pattern is better choice than static class, because maintaining state in static class leads to bugs, especially in concurrent environment, that could lead to race conditions without adequate synchronization parallel modification by multiple threads.
Singleton class can be lazy loaded if its a heavy object, but static class doesn't have such advantages and always eagerly loaded.
With singleton, you can use inheritance and polymorphism to extend a base class, implement an interface and provide different implementations.
Since static methods in Java cannot be overridden, they lead to inflexibility. On the other hand, you can override methods defined in singleton class by extending it.
Disadvantages of static class
Advantages of static class
Detailed description each of them is too verbose so I just put a link to a good article - All you want to know about Singleton
I'm agree with this definition:
The word "single" means single object across the application life cycle, so the scope is at application level.
The static does not have any Object pointer, so the scope is at App Domain level.
Moreover both should be implemented to be thread-safe.
You can find interesting other differences about: Singleton Pattern Versus Static Class
In many cases, these two have no practical difference, especially if the singleton instance never changes or changes very slowly e.g. holding configurations.
I'd say the biggest difference is a singleton is still a normal Java Bean as oppose to a specialized static-only Java class. And because of this, a singleton is accepted in many more situations; it is in fact the default Spring Framework's instantiation strategy. The consumer may or may not know it's a singleton being passed around, it just treat it like a normal Java bean. If requirement changes and a singleton needs to become a prototype instead, as we often see in Spring, it can be done totally seamlessly without a line of code change to the consumer.
Someone else has mentioned earlier that a static class should be purely procedural e.g. java.lang.Math. In my mind, such a class should never be passed around and they should never hold anything other than static final as attributes. For everything else, use a singleton since it's much more flexible and easier to maintain.
We have our DB framework that makes connections to Back end.To Avoid Dirty reads across Multiple users we have used singleton pattern to ensure we have single instance available at any point of time.
In c# a static class cannot implement an interface. When a single instance class needs to implement an interface for a business contracts or IoC purposes, this is where I use the Singleton pattern without a static class
Singleton provides a way to maintain state in stateless scenarios
Hope that helps you..
In an article I wrote I have described my point of view about why the singleton is much better than a static class:
I read the following and think it makes sense too:
Taking Care of Business
Remember, one of the most important OO rules is that an object is responsible for itself. This means that issues regarding the life cycle of a class should be handled in the class, not delegated to language constructs like static, and so on.
from the book Objected-Oriented Thought Process 4th Ed.
There is a huge difference between a single static class instance (that is, a single instance of a class, which happens to be a static or global variable) and a single static pointer to an instance of the class on the heap:
When your application exits, the destructor of the static class instance will be called. That means if you used that static instance as a singleton, your singleton ceased working properly. If there is still code running that uses that singleton, for example in a different thread, that code is likely to crash.
The difference in my head is implementing object oriented programming (Singleton/Prototype) or functional programming(Static).
We are too focused on the number of objects created by singleton pattern when what we should focus on is that in the end we hold an object. Like others have already said, it can be extended, passed as a parameter but most importantly it is state-full.
On the other hand static is used to implement functional programming. The static members belongs to a class. They are stateless.
By the way did you know that you can create singleton static classes :)
getInstance()
method each time you want to use it (although probably in most cases it doesn't matter). – too much phpsingleton
object wherestatic
methods are just functions, a non-OO entity. – fastcodejava