Difference between static class and singleton pattern?
Asked Answered
E

42

2059

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?

Edra answered 6/2, 2009 at 8:13 Comment(8)
Depending on the language implementation and your usage patterns, a Singleton might be less efficient due to the overhead of calling the getInstance() method each time you want to use it (although probably in most cases it doesn't matter).Endocarditis
There are lot of answers already. It is actually a singleton object where static methods are just functions, a non-OO entity.Bilow
Depends upon the implemenation.. csharpindepth.com/Articles/General/Singleton.aspxBonnell
There is a difference when you you want to allow third parties to supply the implementation of the class. In this case you usually need a Factory patterns as well. See agiletribe.wordpress.com/2013/10/08/…Pita
IMO this answer sums it up very well stackoverflow.com/questions/14097656/…Magnify
interesting link: stackoverflow.com/questions/1496629/…Mestee
Singleton are lazily initialized and static are eagerly initialized. So singleton helps saving memorySassoon
Note: Most of the responses are Java related, so in that vein be careful that a static class is only guaranteed to be unique at the class loader level. There can be multiple class loaders in some containers, So it is not always guaranteed that there is one and only one.Approximal
K
1434

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.

Kissinger answered 6/2, 2009 at 8:17 Comment(19)
Well, if you prefer it, neither is inherently threadsafe, you have to make them be threadsafe, both of them, so no difference there.Pacian
Can you give an example of something which is inherently threadsafe, other than immutable types?Kissinger
Even some immutable types are not thread safe if they are copies themselves of a mutable object.Delphine
Jon, by "inherently" I mean from the programmer/user point of view. Lots of system calls or library classes are threadsafe so I don't have to worry about it... but you're right, I can't think of anythingPacian
@WolfmanDragon: I'm not sure I'd call that an immutable type, but yes, it gets woolly. Eric Lippert has a great post about different varieties of immutability.Kissinger
To Skeet: People saying that singleton isn't threadsafe mean that a singleton is shared between threads unnecessarily all the time, while stack objects get shared when you need them to, which means you don't have to do unneeded synchronization.Hilaire
@Iraimbilanja: At that point it all becomes language and platform specific, I'd say.Kissinger
@JonSkeet Can you please explain what you mean by so you can pass around the singleton as if it were "just another" implementation." . Can't you do the same with a class that has a bunch of static methods..I find this question itself a little bit confusing since the questions starts with difference between static class and Singleton and your answer speaks about difference between a singleton and a bunch of static methods. Ofcourse there is no such thing as static class in Java except for static nested class.Les
@Geek: Imagine the singleton implements an interface Foo, and you have a method taking a Foo as a parameter. With that setup, callers can choose to use the singleton as the implementation - or they could use a different implementation. The method is decoupled from the singleton. Compare that with the situation where the class just has static methods - every piece of code which wants to call those methods is tightly coupled to the class, because it needs to specify which class contains the static methods.Kissinger
Singletons which implements some interface are preffered in case you will need to unit test your code. if your code contain calls to static interfaces, it will not be possible to mock it.Courtnay
@AmirBareket: Why? They're largely equivalent for unit testing - both are horrible, basically, because they both rely on global state. For testability you should avoid both options.Kissinger
you right but sometimes you have to use it.so in case your singleton implements some interface and you create the instance by a factory, you could then create a different instance for testing purpose.check the factory singelton pattern. i have try it. if you have calls to static methods, it will be propblematic to mock the return value.Courtnay
@AmirBareket: So that's testing other code, not the singleton itself. And if you've got a factory anyway and are injecting the instance elsewhere, why bother having a singleton? You can make the factory always return the same instance without following the singleton pattern.Kissinger
@Jon Skeet: yes testing a code that uses a singleton ( or static method). and yes this is exactly what i mean. And this is why i call this factory singleton. because this is a factory that return always the same instance. it means that this instance is a singleton in the system. and this is why this is preferred than static methods. of course, you will need to add a method setInstance(IObject instance) to be used in the testing.Courtnay
@AmirBareket: It's not a singleton according to the singleton design pattern though - if the class itself allows multiple instances to be created, it's not a singleton IMO, regardless of what the factory does.Kissinger
@Jon Skeet: This is true, someone can create it not from the factory and this is not a fully singleton compatible, from the design pattern perspective. nevertheless , it is testable code. if developer follow the instruction of creating instance from the factory, there will be only one instance and the code could be testable. I don’t see an approach of testing code that calls static methods which is better than this, and this is my point. If you have something please tell.Courtnay
@AmirBareket: No, that's absolutely fine, and I do something similar... I normally configure whichever DI framework I'm using to happen to inject the same object everywhere, when I want to. (No factory class with that as a requirement - it's just part of DI configuration.) My point is that this question is about the singleton pattern vs static methods, whereas the approach you're talking about is neither of those.Kissinger
Note that C++11 entities ought to be thread-safe (from compiler aspect).Anselmi
Just wanted to point out that Java enums are singletons, share a common base class, and can implement an interface if anyone was looking for a real world exampleCoinage
H
543

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.

Hayley answered 6/2, 2009 at 8:21 Comment(13)
Why would you pass a Singleton as a parameter, though, if you can access the same instance from just about anywhere by calling the static getInstance() method?Eximious
@HenriqueOrdine So it can fit into existing code and provide an interface?Unquestionable
I see, yes. I don't see why you can't pass a Class with a bunch of static methods as a parameter though, in that case, as you can still instantiate these Classes.Eximious
@HenriqueOrdine They are speaking about static class, not a class with static methods. Static class cannot be instantiated. Nevertheless, if you pass an instance of a (non-static)class that contains static methods, you cannot call static methods on an instance.Indignation
What's a static class? At least in Java, there's no such thing.Eximious
Also, in Java, in CAN very well call static methods on an instance variable. You'll get a warning, because you won't manage any polymorphism with that, but you can do it if you like.Eximious
@HenriqueOrdine Jon Skeet states what a static class is. You're right, there's no such thing in Java (unless you have a nested static class). All it's saying is that any such method declarations in that class are going to be static. I'm not sure why you're pointing out static classes though, Jon was only stating what a static class is because of the context of the question, it's irrelevant to this question.Hayley
@Kezzer, I'm sorry about the misunderstanding. I wasn't referring to any statements from Jon Skeet, I was referring to Goran's statement above mine, where he says: "@HenriqueOrdine They are speaking about static class, not a class with static methods".Eximious
@Indignation I was initially very confused by your wording. You said "you cannot call static methods on an instance". I read that as "if you have a reference to an instantiated object, you cannot call any static methods it may have." That is of course, incorrect. After reading it again a few times I think you meant "from inside static methods you cannot access non-static objects in the class" which is correct. Want to clarify that for anyone new to these concepts who comes across this answer and reads your comments.Communard
@AndrewSteitz Since I am programming only in .NET, in that environment my statement is correct. create a class called Test, which contains a public static void A() and public void B(). If you instantiate Test class; Test t = new Test(), you cannot call static method A() on t (t.A();), you can call it only on Test class (Test.A();)Indignation
@goran Not directly on the Instance, but you can still use typeof(XX) or XX.getType(), combined with getMethod("YY") and invoke. Eg typeof(ObjXX).GetMethod("theMethodName").invoke(); So it IS possible, just crazy ugly to write...Embosom
@Embosom What you are actually doing is calling static method on a type, not on instance. Calling a instance.ToString().Length does not mean that instance supports Length property, does it?Indignation
In Java, static class can have instance methods as well. Code it, will compile with ease.Tannatannage
D
399
  1. Singleton objects are stored in the heap, but static objects are stored in the stack.
  2. We can clone a singleton object as long as the designer allows it, but we cannot clone a static class object.
  3. Singleton classes follow object-oriented programming (OOP) principles; static classes do not.
  4. We can implement an interface through a singleton class, but not through the static methods of a class (or through a static class available in e.g. C#).
Damicke answered 11/9, 2012 at 10:22 Comment(26)
The second statement is wrong. We can't clone Singleton object. Singleton implementation must refuse this. If you really can clone Singleton, it's not Singleton.Sickener
This is answer is not correct for Java: neither the singleton nor the static uses the stack.Pita
#1 is not important. #2 describes a defective implementation. #3 is completely unjustifiable.Gusty
#1. why static objects are always in stack. I don't know about java but in c++ when we say an object in stack, the memory allocated for members should reside in stack memory.By default for all static data members will go to data segment and for remaining members based on where/how it is getting instantiated. with 'new' will go to heap, global or static will go to data segment and local object in stack.Poitiers
#1 stack provides faster retrieve. It might be important in some cases.Gameto
How can static object be stored in stack? New stack frame is created when you invoke a method, it stores method's local variables, this stack frame is removed when the method returns, and those local variables are lost. Sure stack is fast, but it is not suitable to store static objects.Coffeepot
A singleton, in Java at least, can have more than one instance in the same JVM even when implemented "properly". You would need to have the same serialized object, and deserialize it more than once using different instances of ObjectOutputStream, or by calling ObjectOutputStream.reset() on the same instance after each deserialization. And likewise with serialization, if you serialize an object twice you get two instances if the stream closes or is reset since the object graph closes with it. Not quite the same as cloning, but it does break the pattern.Solanum
Continuing with Mar 5 at 14:49 @emodendroket comment: #4 Proves false in Objective-CJuice
Isn't a Static Class just on the Loader Heap,so the Heap, which doesn't get checked by the GC?Esquimau
A singleton may or may not be on the stack, it depends on how its implemented (in c++).Driftwood
A singleton needs to be in heap always. Otherwise is not a singleton. Why? Because a singleton promises that a single instance of that class will be alive during the entire execution of the program. The only way a program can do that is by making that instance static, which consequently moves the variable to the heap. In other words, each function has its own portion of the stack to run that gets destroyed when the function returns.So anything that lives there will be destroyed sooner or later. Which again, goes against Singleton principles.Cruiser
This is answer is not correct for C#: Static classes are stored in the High Frequency HeapStempien
I cannot understand the number of upvotes on this one. 1) Why should Singleton have to be stored in stack? In managed languages like C# or Java data is stored in a managed heap, except for local method variables/parameters. 2) If you can clone it, then it's not a properly implemented singleton. 3) Singleton is known as a OOP anti-pattern; i.e. something that you should avoid if possible. 4) This is the only thing that's correct.Altorelievo
static class can implement interface, I could compile it.Tannatannage
static object does not get store in stack explained in this article stackoverflow.com/questions/8387989/…Foin
@Tannatannage This is not what the OP meant. You cannot describe the class by it's implemented interface, e.g. if you have class A implements B, you can't have B b = A.class. You can, however, do B b = A.getInstance() if getInstance() returns the singleton.Commemorative
@Commemorative : Why will someone do like B b = A.class and Not B b = new A. If you write wrong syntax and still expect it work that's not where jvm can help.Tannatannage
@Tannatannage I did not say that it is legal syntax, or that I'd expect it to work. What the OP meant by "a static class can not implement an interface" was that a class can not implement an interface that defines its static methods. So if you needed an object of an interface somewhere, you could not "use" that class in the same sense you can use the singleton object whose class implements said interface.Commemorative
@Adowrath: Well that's for all classes NOT in particular with Static class. Mentioning that as a specific difference with respect to Static class is wrong as it applies to all classes - If you go by interface type which a class implement you cannot take advantage of non-interface methods. And mentioning that static methods cannot implement interfaces is TOTALLY wrong. If you something else, mention that not the wrong thing. What one means should what they should write as well.Tannatannage
@Tannatannage I think we are interpreting the term "static class" differently. You, as it seems to me, mean the "normal" meaning of it being a nested class, but me and OP mean a class in the sense of only it's static interface. But I think this is getting Off-topic, so I'd say we'll leave it at that.Commemorative
Static objects are not stored on stack. In C#, static objects go to a special memory area called high-frequency heap along with the Type instance. Static classes don't have an instance of their own which can really be called as objects. There are just static fields which get stored in Type instance. Have a look at this post.Dumfound
All 4 justifications are plain hogwash.Substituent
The Static variables or static classes are not stored in the Stack memory. There is some specific space in Heap memory called High-Frequency Heap where the static classes and static variables are stored. This space is beyond the scope of Garbage Collector and hence, the memory gets released only when the corresponding Process or AppDomain gets unload.Gusta
Add number 5. The earth is flat.Vargueno
An small saucy example of #3: In some languages, including PHP and C++, you cannot use fluent interface with static methods, but you can with Singleton pattern.Cymar
I agree with @Altorelievo regarding the memory allocation for static objects. Both Singleton and static are stored on the Heap memory, but static classes are stored in a special area of the Heap Memory called the High-Frequency Heap (Objects in High Frequency Heap are not garbage collected by GC, and hence static members are available throughout the application lifetime). Ref: henriquesd.medium.com/….Minni
S
196

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.

Summerwood answered 6/2, 2009 at 8:30 Comment(3)
+1 for good, pragmatic points. Singleton pattern is overused in general, but there are a few situations where it is fitting. See also: agiletribe.wordpress.com/2013/10/08/…Pita
You are right about advantage of being polymorphic. This is the most important pointRooke
Nested static class can implement interface. Try coding it, will work. I could compile the code without any error.Tannatannage
S
95

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.

Slaw answered 30/12, 2010 at 20:55 Comment(8)
Why should static classes not do anything which needs to save state?Jeer
@Trisped: You have neither precise control over initialization nor finalization.Slaw
you lost me at "Singleton is my favorite pattern". Singleton is such a sharp corner that it should be considered an anti-pattern as well as a pattern. Classes can well have static states, that's also single access, if anything static state is more "single access" than singletons because most singleton implementations are broken ie. you can clone the singleton, while static is blessed by the definition to be unique.Orest
What does it mean to maintain state? What is state?Overdraft
@KyleDelaney: Simply State is the combination of different properties of an object which usually change over time. You can Google for formal definition.Slaw
If you need precise control over initialization then can't you just make a static initialize method?Overdraft
In case someone sees this comment, please, use Dependency Injection aka IoC instead of Singleton wherever it is possible.Barolet
@KyleDelaney: "If you need precise control over initialization then can't you just make a static initialize method? ". In that sense you can implement OO in procedural code and reinvent the wheel. Afterall OOP is a paradigm for managing complexity and at best (compiler optimization) works as fast the same code written as procedural, so speed is traded off for managing complexity. Your other question could be answered the same way, that static class with static fields misses OO` benefits i.e. inheritance.Slaw
C
93

Static Class:-

  1. You cannot create the instance of static class.

  2. Loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.

  3. We cannot pass the static class to method.

  4. We cannot inherit Static class to another Static class in C#.

  5. A class having all static methods.

  6. Better performance (static methods are bonded on compile time)

Singleton:-

  1. You can create one instance of the object and reuse it.

  2. Singleton instance is created for the first time when the user requested.

  3. You can create the object of singleton class and pass it to method.

  4. Singleton class does not say any restriction of Inheritance.

  5. We can dispose the objects of a singleton class but not of static class.

  6. Methods can be overridden.

  7. Can be lazy loaded when need (static classes are always loaded).

  8. We can implement interface(static class can not implement interface).

Carin answered 1/6, 2015 at 11:42 Comment(7)
Static classes do have constructors: msdn.microsoft.com/en-us/library/k9x6w0hc.aspxUpwind
Yes, static can have constructor which is internal to that class. This gets invoked when any static method in the class is called.Rocketry
For singleton on compile time, it is stored in the HEAP memory but if it gets instantiated once does it get stored in STACK?Unbearable
@Unbearable No. Any singleton instance is an object instance at the end of the day. It will get stored on heap without doubt.Dumfound
@Rocketry Important distinction: the constructor also gets invoked before the first (AKA only) instance is created.Petigny
seems to be the most complete answer, for point 3 Static Class: I would add cannot have destructor or FinalizerCollen
"Singleton instance is created for the first time when the user requested." This second point about Singleton is not entirely true because we can implement an "Eager loaded" singleton as well.Interlunar
L
54

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.

Ligature answered 6/2, 2009 at 8:35 Comment(4)
polymorphism doesn't come into play with singletons at allHilaire
So you think. I think differently. ;) For instance, imagine a singleton factory that returns an interface. You know you're getting an ISingleton (and it's the same one forever) but not necessarily which implementation.Ligature
Nested static class can have instance methods as well, its not restricted to have only static methods.. Code it and you can see.Tannatannage
In languages with a nicer object model (e.g. Ruby), classes are objects too. The "purely procedural" aspect of a static class is an arbitrary restriction imposed by the language.Chief
I
37

In singleton pattern you can create the singleton as an instance of a derived type, you can't do that with a static class.

Quick Example:

if( useD3D )
    IRenderer::instance = new D3DRenderer
else
    IRenderer::instance = new OpenGLRenderer
Imitate answered 6/2, 2009 at 8:16 Comment(5)
It's not really a singleton pattern, looks more like factory to me.Brasilein
Not really, the fundamental difference between the two is that the Singleton will "cache" its single object and keep returning (a reference to) the same one. The Factory pattern will create new instances.Flashy
Then it's proxy-singleton :)Brasilein
Hmm, I know this variety of the Singleton as MonoState.Foreordain
example is factory patternFlabellum
M
29

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.

Margaretamargarete answered 20/12, 2012 at 21:53 Comment(7)
I don't think you can directly mock a singleton. Wouldn't you have to declare an interface that the singleton and the mock class both implement?Cosmetician
@espertus Why cant you mock your singleton? Example using mockito MySingleton mockOfMySingleton = mock(MySingleton.class).Margaretamargarete
you're right, you can mock it with tools like mockito that use reflection. I meant that you can't mock it directly by subclassing it and overriding its methods.Cosmetician
@espertus Why not? When you instantiate the object you are testing you can substitute the subclass implementation of your singleton wherever you would have used the original. Ex: new ClazzToTest(mockSingleton);Margaretamargarete
I haven't used Mockito, but how can you subclass a class that has a private constructor, which is the case for singletons, except by using reflection? Related discussions: https://mcmap.net/q/19820/-mocking-a-singleton-class stackoverflow.com/questions/15939023/…Cosmetician
@espertus If your singleton is implemented like the examples on Wikipedia then it does become very difficult to mock. In this case I would strongly recommend a mocking frame work like Mockito. Another option would be to use a framework like Spring to define and access singletons, this removes a lot of the complexity of working with singletons. Here is an example, using Spring, that does not use a private constructor.Margaretamargarete
Okay. I guess I should have said: If you implement singleton by making the constructor private, you can't mock it without using reflection or without creating an interface that the singleton and the mock class both implement.Cosmetician
A
26

Here's a good article: http://javarevisited.blogspot.com.au/2013/03/difference-between-singleton-pattern-vs-static-class-java.html

Static classes

  • a class having all static methods.
  • better performance (static methods are bonded on compile time)
  • 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");
        }
    }
    

Singleton

In summary, I would only use static classes for holding util methods, and using Singleton for everything else.


Edits

Attaboy answered 24/4, 2014 at 1:22 Comment(6)
I don't know about java, but in .Net, your last two points are incorrect. Static classes can reference static properies and fields, so on state they are equal. And they are lazy loaded -- the static constructor is run when: 1) An instance of the class is created. 2) Any of the static members of the class are referenced. 1 doesn't apply, which leaves 2. So, a static class is not loaded until the first time it is used.Mammillate
For static class, though you can't override the static method, you can hide the static method from its parent.Zuzana
if Animal animal = new Cat(); then animal.foo(); what happens?Unbearable
@Mammillate static class is not loaded until the first time use? I believe it is stored in the stack memory on compile time. And it is instantly accessed.. isnt it?Unbearable
@Luminous_Dev: at least for .net, a static class has a constructor that runs when first accessed, so no it is not instantly accessible. The static constructor could in theory take an unbounded amount of time. Where it (or any other class is stored) is an implementation detail, that is not really relevant to this question.Mammillate
Singleton is preferred in case we the class have a state (state management = bunch of fields)Leavings
K
25

Another advantage of a singleton is that it can easily be serialized, which may be necessary if you need to save its state to disc, or send it somewhere remotely.

Kenogenesis answered 8/8, 2011 at 3:36 Comment(0)
H
19

Singleton's are instantiated. It's just that there's only one instance ever created, hence the single in Singleton.

A static class on the other hand can't be instantiated.

Hayley answered 6/2, 2009 at 8:15 Comment(1)
Static class can be very much instantiated in java . Read docs.oracle.com/javase/tutorial/java/javaOO/nested.html . Also refer my answer https://mcmap.net/q/19809/-difference-between-static-class-and-singleton-patternTannatannage
D
19

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.

Dough answered 16/8, 2009 at 15:54 Comment(1)
Yes, everyone else seems to ignore the fact that a class with static methods can also have private static fields which it can still use to maintain state (and expose some of them to the client code via public static setters/getters).Keewatin
A
18

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();
    }
}
Antitrust answered 9/6, 2013 at 23:49 Comment(0)
R
13

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.

Rouvin answered 6/2, 2009 at 9:36 Comment(0)
E
13

Main differences are:

  • Singleton has an instance/object while static class is a bunch of static methods
  • Singleton can be extended e.g. through an interface while static class can't be.
  • Singleton can be inherited which supports open/close principles in SOLID principles on the other hand static class can't be inherited and we need to make changes in itself.
  • Singleton object can be passed to methods while static class as it does not have instance can't be passed as parameters
Elisavetgrad answered 28/4, 2018 at 16:12 Comment(0)
J
10

Distinction from static class

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

  • It is easier to write unit test for singleton than static class, because you can pass mock object whenever singleton is expected.

Advantages of static class

  • Static class provides better performance than singleton, because static methods are bonded on compile time.

There are several realization of singleton pattern each one with advantages and disadvantages.

  • Eager loading singleton
  • Double-checked locking singleton
  • Initialization-on-demand holder idiom
  • The enum based singleton

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

Jabon answered 27/1, 2020 at 10:9 Comment(0)
C
7

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.

Courtnay answered 13/4, 2014 at 12:55 Comment(3)
That's now not thread safe, and generally nasty in terms of how you access the interface implementation. Sure, having an interface is nice for testability - but then why bother with a singleton? Just avoid having a singleton at all; have one class implementing it for production purposes, one implementation for test purposes, and inject the right instance depending on what you're doing. No need to couple the singleton to its callers at all.Kissinger
thanks for the feedback. it is very simple to make it thread safe. in addition ,i use singleton for caching purpose.Courtnay
Yes, although with pointless overhead. Again, it's just simpler not to use a singleton.Kissinger
J
6

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

Jequirity answered 11/2, 2016 at 15:8 Comment(0)
C
5

One notable difference is differed instantiation that comes with Singletons.

With static classes, it gets created by the CLR and we have not control on it. with singletons, the object gets instantiated on the first instance it's tried to be accessed.

Chrysotile answered 27/6, 2012 at 14:3 Comment(0)
H
5

Below are some main differences between static class and singleton:

1.Singleton is a pattern, not a keyword like static. So for creating a static class static keyword is sufficient while in the case of singleton there is a need to write the logic for the singleton.

2.A singleton class must have a private default instance constructor, while a static class cannot contain any instance constructor.

3.A static class is neither instantiated nor extended, while a singleton class can be.

4.A static class is sealed implicitly, but the singleton class must be decorated as sealed explicitly.

5.It is possible for a singleton to implement the interface or inherit from another class, but the static class neither implements the interface nor extends from any other class.

6.We cannot implement the dependency injection with a static class, but DI is possible with the singleton class because it can be interface driven. The scope of the static class is at the app domain level because it is managed by the CLR, while the scope of the singleton object is across the application lifecycle.

7.A static class cannot have any destructor but a singleton class can define a destructor.

8.The singleton class instance can be passed as a parameter to another method while a static class cannot be because it contains only static members.

Hotel answered 19/6, 2022 at 13:15 Comment(0)
L
4
  1. Lazy Loading
  2. Support of interfaces, so that separate implementation can be provided
  3. Ability to return derived type (as a combination of lazyloading and interface implementation)
Lermontov answered 8/5, 2012 at 16:34 Comment(1)
Nested static class can very much implement interface in java. Your second point is Wrong.Tannatannage
V
4

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.

Vicarial answered 7/6, 2012 at 1:7 Comment(0)
T
4

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

Twocycle answered 27/6, 2012 at 9:58 Comment(0)
M
4

In an article I wrote I have described my point of view about why the singleton is much better than a static class:

  1. Static class is not actually canonical class – it’s a namespace with functions and variables
  2. Using static class is not a good practice because of breaking object-oriented programming principles
  3. Static class cannot be passed as a parameter for other
  4. Static class is not suitable for “lazy” initialization
  5. Initialization and using of static class is always hard tracked
  6. Implementing thread management is hard
Manville answered 13/11, 2013 at 10:56 Comment(2)
I would brush it up for english grammar, but otherwise, it is an interesting read :)Luxor
This is better answer as deals with the real use case specific problem rather than implementation details.Rhythmist
V
4
  • Singleton class provides an object(only one instance) during the application lifeCycle such as java.lang.Runtime

    While Static class only provide static methods such as java.lang.Math

  • Static methods in Java cannot be overridden, but methods defined in Singleton class can be overridden by extending it.

  • Singleton Class is capable of Inheritance and Polymorphism to extend a base class, implement an interface and capable of providing different implementations. whereas static not.

For eg: java.lang.Runtime,is a Singleton Class in Java, call to getRuntime() method returns the runtime object associated with the current Java application but ensures only one instance per JVM.

Vergievergil answered 12/5, 2020 at 12:23 Comment(0)
T
3

a. Serialization - Static members belong to the class and hence can't be serialized.

b. Though we have made the constructor private, static member variables still will be carried to subclass.

c. We can't do lazy initialization as everything will be loaded upon class loading only.

Tarantass answered 14/1, 2014 at 17:46 Comment(0)
D
3

From a client perspective, static behavior is known to the client but Singleton behavior can be completed hidden from a client. Client may never know that there only one single instance he's playing around with again and again.

Drumfish answered 4/8, 2014 at 6:23 Comment(0)
D
3

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.

Deutzia answered 30/12, 2015 at 21:5 Comment(1)
I would disagree, as this really just adds a responsibility to the class, which (assuming it does anything) means it now violates the Single Responsibility Principle.Procne
C
3
  1. We can create the object of singleton class and pass it to method.

  2. Singleton class doesn't any restriction of inheritance.

  3. We can't dispose the objects of a static class but can singleton class.

Centigrade answered 18/10, 2016 at 18:58 Comment(1)
What is the use of passing a singleton into a method if there's always only one and that one always has a static reference?Mezcaline
R
3

A static class in Java has only static methods. It is a container of functions. It is created based on procedural programming design.

Singleton class is a pattern in Object Oriented Design. A Singleton class has only one instance of an object in JVM. This pattern is implemented in such a way that there is always only one instance of that class present in JVM.

Ripieno answered 9/6, 2018 at 1:12 Comment(0)
S
2

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.

Spherule answered 31/3, 2014 at 13:33 Comment(2)
So if application exits will Singleton still remain in memory?Tannatannage
I think you mean when your current thread exits, not the application, right? If the application exits, there's no way for another thread to use anything from it.Mestee
T
2

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

Tildi answered 8/9, 2017 at 9:47 Comment(1)
What is the point of passing a singleton as a parameter since it always has a static reference on the class?Mezcaline
G
2

The most important point that you need to keep in mind is that Static is a language feature whereas Singleton is a Design Pattern. So both belong to two different areas. With this kept in mind, let’s proceed and discuss the differences between Singleton vs Static class in C#.

We cannot create an instance of a static class in C#, yes one copy of the static class is available in memory, but as a developer, we cannot create an instance of the static class. But, as a developer, we can create a single instance of a singleton class and then we can reuse that singleton instance at many different places of the application.

When the compiler compiles the static class then internally it treats the static class as an Abstract and Sealed Class in C#. This is the reason why neither we create an instance nor we can use the static class as the child class in inheritance. On the other hand, we can create a single instance of the Singleton class as well as we can also use the Singleton class as a child class in C#.

The Singleton Class Constructor is always marked as private. This is the reason why we cannot create an instance from outside of the singleton class. It provides either public static property or a public static method whose job is to create the singleton instance only once and then return that singleton instance each and every time we called that public static property/method from outside of the singleton class.

A Singleton class can be initialized lazily or can be loaded automatically by CLR (Common Language Runtime) when the program or namespace containing the Singleton class is loaded i.e. Eager Loading. Whereas a static class is generally initialized when it is loaded for the first time and it may lead to potential classloader issues. It is not possible to pass the static class as a method parameter whereas we can pass the singleton instance as a method parameter in C#.

In C#, it is possible to implement interfaces and inherit from other classes. That means it allows inheritance with the Singleton class. The Singleton class can be created as a Child class also only, you cannot create child classes from the Singleton class. These are not possible with a static class. So, the Singleton class is more flexible as compared to the Static Classes in C#.

We can clone the Singleton Class object (both Deep Copy and Shallow Copy of the Clone Object is possible using the MemberwiseClone method) whereas it is not possible to clone a static class. It is possible to dispose of the objects of a singleton class whereas it is not possible to dispose of a static class.

We cannot Implement the Dependency Injection Design Pattern using the Static class because the static class is not interface-driven.

Singleton means a single object across the application lifecycle, so the scope is at the application level. As we know the static class does not have any Object pointer, so the scope is at the App Domain level.

Reference: https://dotnettutorials.net/lesson/singleton-vs-static-class/

Gambell answered 21/3, 2023 at 20:44 Comment(0)
C
1

When I want class with full functionality, e.g. there are many methods and variables, I use singleton;

If I want class with only one or two methods in it, e.g. MailService class, which has only 1 method SendMail() I use static class and method.

Corinacorine answered 27/5, 2012 at 22:42 Comment(0)
G
1

As I understand the difference between a Static class and non-Static Singleton class, the static is simply a non-instantiated "type" in C#, where the Singleton is a true "object". In other words, all the static members in a static class are assigned to the type but in the Singleton are housed under the object. But keep in mind, a static class still behaves like a reference type as its not a value type like a Struct.

That means when you create a Singleton, because the class itself isnt static but its member is, the advantage is the static member inside the Singleton that refers to itself is connected to an actual "object" rather than a hollow "type" of itself. That sort of clarifies now the difference between a Static and a Non-Static Singleton beyond its other features and memory usage, which is confusing for me.

Both use static members which are single copies of a member, but the Singleton wraps the referenced member around a true instantiated "object" who's address exists in addition to its static member. That object itself has properties wherein in can be passed around and referenced, adding value. The Static class is just a type so it doesn't exist except to point to its static members. That concept sort of cemented the purpose of the Singleton vs Static Class beyond the inheritance and other issues.

Gorton answered 7/7, 2017 at 16:22 Comment(0)
C
1

A singleton is nothing more than a write-once static variable on a class that always refers to the same instance of itself once it's initialized.

So, you cannot "use a singleton instead of static variables" nor can you avoid keeping state in static variables by using singletons.

The advantage of a singleton is only this: it does not get reinitialized even if some other code tries to reinitialize it a thousand times. This is great for something like a network handler where, y'know, it would suck if an instance got replaced with another instance in the middle of waiting for a response.

Unless you want an entire app WITH NO INSTANCES ANYWHERE—all static!—then the singleton makes sense for these cases where we cannot rely on a lack of human error as the only guarantee something won't get overwritten.

But beware, singleton is no guarantee against state living everywhere. Your network handler may within itself also rely on other singletons, etc. Now we have state living in a host of singletons... marvelous.

And there is no compiler in existence that will ensure that the singleton is where all your state lives, or any other such ideas, at compile time. You can have a hundred static variables on a class that has a singleton. And the singleton can access the static variables. And the compiler will not care.

So I would caution anyone from assuming that using a singleton guarantees anything at all about where state lives. Its only guarantee is simply that it is the only instance of its class, ever. And that is also its only advantage.

Any other advantages that the other answers claim for singletons are things the compiler does not guarantee and that may vary from language to language. Dependency injection is a supplementary pattern that may rely on a singleton, though it may or may not be the best solution or the only solution in a given language. In languages that lack generics, or that place arbitrary restrictions on calling static accessors and functions, resorting to the singleton pattern may indeed be the best available solution to a given problem.

Singleton is not necessary at all in a language like Swift, to get dependency injection, testable code, well-managed state, thread-safe accessors, polymorphism, etc. However it's still useful for the guarantee of a single instance ever.

To recap: a singleton is nothing more than a static variable that serves as a safeguard against multiple instances of given class existing, and against the single instance being overwritten by a new one. That's it, period, full stop.

Coda answered 27/1, 2020 at 23:41 Comment(0)
C
0

Example with a static class

public class Any {

    private static Any instance = new Any();

    private Singleton() {
        System.out.println("creating");
    }
}

with singleton patterns only exist one instance:

public class Singleton {

    private static Singleton instance = new Singleton();

    private Singleton() {
        System.out.println("creating");
        if (instance != null) {
            throw new RuntimeException("Imposible create a new instance ");
        }
    }
}
Carib answered 3/6, 2019 at 21:1 Comment(2)
The above example isn't a static class.Mezcaline
What's the point of having a singleton if you instantiating it?Monopolize
T
0

static classes usually are used for libraries, singletons are used if I need only one instance of a particular class. From the point of view of memory there are some differences though: usually in the heap there are allocated only objects, the only methods allocated are methods that are current running. a static class has all methods static too and that will be in the heap from begin, so in general the static class consume more memory.

Toy answered 5/2, 2021 at 16:2 Comment(3)
All depends on the compiler. There's so many languages and so many compilers. Some use heap some don't.Nicolis
true, I was implicitly talking about jvmToy
but in general if a language use objects then use also heap, what they can avoid using is the garbage collectorToy
P
-1

One main advantage for Singleton : Polymorphism Eg : create instance using a Class factory( Say based on some configuration), and we want this object to be really singleton.

Papagena answered 24/5, 2013 at 23:58 Comment(0)
T
-2

Both can be invoked without instantiation, both provide only one "Instance" and neither of them is thread-safe. Is there any other difference?

The question is wrong, both its statements. Please note: that static class here means nested static class And not a class with only static methods.

I am assuming(i.e. static class meaning nested static class and not a class with only static members) so because if I see most popular Singleton implementation i.e. DCL way, its nothing but static declaration of instance and static method to get the Singleton instance. Its one implementation. So in this case what's the difference between Singleton and a class with only static members. Though other implementations are possible like that using Enum.

Let me correct the statements:

  1. Singleton class can have single instance application-wide. Nested static class can have multiple instance(see the code below as a proof). Read the basics of nested class here.

  2. No class is inherently thread-safe, it has to be made thread-safe programmatically. It can be done for both nested static class and Singleton.

Some more myth busters are below(Most of answers to this question has given these statements so thought it would be good to programmatically prove it):

  1. Nested static class can implement interface like any other class.
  2. Nested static class can extend other non-final class.
  3. Nested static class can have instance variables.
  4. Nested static class can have parameterized constructor(s).

In the code below you can see that nested static class NestedStaticClass implements interface, extends another class, have instance variable and parameterized constructor.

 package com.demo.core;

    public class NestedStaticClassTest
    {
        public static void main(String[] args)
        {
            OuterClass.NestedStaticClass obj1 = new OuterClass.NestedStaticClass();
            OuterClass.NestedStaticClass obj2 = new OuterClass.NestedStaticClass();

            if(obj1 == obj2)
            {
                System.out.println("Both nested static objects are equal....");
            }
            else
            {
                System.out.println("NOT EQUAL......");
            }

            System.out.println(OuterClass.NestedStaticClass.d);

            obj1.setD(5);

            System.out.println(OuterClass.NestedStaticClass.d);

            System.out.println(obj1.sum());
        }
    }

    class OuterClass
    {
        int a =1;
        static int b = 2;

        static class NestedStaticClass extends OneClass implements Sample
        {
            int c = 3;
            static int d = 4;

            public NestedStaticClass()
            {
            }

            //Parameterized constructor
            public NestedStaticClass(int z)
            {
                c = z;
            }

            public int sum()
            {
                int sum = 0;
                sum = b + c + d + getE();
                return sum;
            }

            public static int staticSum()
            {
                int sum = 0;
                sum = b + d;
                return sum;
            }

            public int getC()
            {
                return c;
            }
            public void setC(int c)
            {
                this.c = c;
            }
            public static int getD()
            {
                return d;
            }
            public static void setD(int d)
            {
                NestedStaticClass.d = d;
            }
        }
    }

    interface Sample
    {

    }

    class OneClass
    {
        int e = 10;
        static int f = 11;

        public int getE()
        {
            return e;
        }
        public void setE(int e)
        {
            this.e = e;
        }
        public static int getF()
        {
            return f;
        }
        public static void setF(int f)
        {
            OneClass.f = f;
        }

    }
Tannatannage answered 9/5, 2016 at 11:31 Comment(5)
Who said this had anything to do with Java's "nested static class?" The question is about singleton vs. static design patterns, and doesn't mention Java at all. Java doesn't have a built-in notion of a purely static class in the way that many other languages do, but even among Java experts the phrase "static class" means "a class, having all static methods".Encratis
@StriplingWarrior: I am assuming so(i.e. static class meaning nested static class and not a class with only static members) because if I see most popular Singleton implementation i.e. DCL way, its nothing but static declaration of instance and static method to get the Singleton instance. Its one implementation. So in this case what's the difference between Singleton and a class with only static members. Though other implementations are also possible like that using Enum.Tannatannage
I don't really follow your logic. The Singleton Pattern (regardless of implementation) implies that there is one (and only one) instance. That doesn't change the definition of a static class, nor does it imply the use of Java. Also, it wouldn't make sense to ask what the difference is between using a Singleton and Java's nested static class, because they serve two completely different purposes--it would be like asking the difference between iPhone and Chevy.Encratis
yes, singleton means single instance in app. So do you mean to say that more than one instance cannot be created for a class with only static members?Tannatannage
I mean to say that if you have a class with only static members, you would never instantiate it at all (whereas a singleton manages its own instance, so consuming code would never instantiate it directly). So if you're thinking of using a singleton pattern, you might wonder why you need to have an instance at all: if you just store your state in static fields on the class, and all your methods are static, then there's no reason to have even one instance of the class, right? That's the essence of this question: what's the practical difference between these two patterns?Encratis
L
-2

I'll try to rise above the WTMI and WTL;DR responses.

Singletons are an instance of an object... full stop

Your question is fundamentally asking about the difference between a class an an instance of that class. I think that's pretty clear and requires no elaboration.

The singleton's class generally takes steps to ensure construction of one instance; that's smart but it's not required.

Example: var connection = Connection.Instance;

Say this is the Connection class:

public sealed class Connection 
{
    static readonly Connection _instance = new Connection();

    private Connection() 
    {
    }

    public static Connection Instance
    {
        get
        {
           return _instance;
        }
    } 
}

Note that you can throw an interface on that class and mock it for testing purposes, something you cannot easily do with a static class.

Laius answered 16/8, 2016 at 20:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.