By Jorge Córdoba


2009-02-06 08:13:22 8 Comments

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?

30 comments

@x-rw 2019-06-03 21:01:32

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 ");
        }
    }
}

@Aaron Franke 2019-11-20 22:52:25

The above example isn't a static class.

@Xaqron 2010-12-30 20:55:55

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.

@Trisped 2012-10-09 21:24:28

Why should static classes not do anything which needs to save state?

@Xaqron 2013-01-03 23:55:03

@Trisped: You have neither precise control over initialization nor finalization.

@PoweredByRice 2017-02-25 06:21:06

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.

@Kyle Delaney 2017-05-18 23:44:02

What does it mean to maintain state? What is state?

@Xaqron 2017-05-18 23:59:19

@KyleDelaney: Simply State is the combination of different properties of an object which usually change over time. You can Google for formal definition.

@Kyle Delaney 2017-05-19 13:23:14

If you need precise control over initialization then can't you just make a static initialize method?

@V.7 2019-11-03 19:04:55

In case someone sees this comment, please, use Dependency Injection aka IoC instead of Singleton wherever it is possible.

@Xaqron 2019-11-10 09:45:28

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

@Premraj 2018-06-09 01:12:56

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.

@Faran Shabbir 2018-04-28 16:12:57

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

@JackDev 2014-04-24 01:22:03

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

@jmoreno 2015-01-26 16:44:45

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.

@Max Peng 2017-09-04 15:57:18

For static class, though you can't override the static method, you can hide the static method from its parent.

@Luminous_Dev 2017-10-29 00:34:38

if Animal animal = new Cat(); then animal.foo(); what happens?

@Luminous_Dev 2017-10-29 00:41:27

@jmoreno 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?

@jmoreno 2017-10-29 01:00:34

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

@Atif Karbelkar 2017-09-08 09:47:06

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

@Aaron Franke 2019-11-20 23:01:13

What is the point of passing a singleton as a parameter since it always has a static reference on the class?

@Stokely 2017-07-07 16:22:52

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.

@Jon Skeet 2009-02-06 08:17:44

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.

@Jorge Córdoba 2009-02-06 08:20:32

Well, if you prefer it, neither is inherently threadsafe, you have to make them be threadsafe, both of them, so no difference there.

@Jon Skeet 2009-02-06 08:23:01

Can you give an example of something which is inherently threadsafe, other than immutable types?

@WolfmanDragon 2009-02-06 08:25:15

Even some immutable types are not thread safe if they are copies themselves of a mutable object.

@Jorge Córdoba 2009-02-06 08:32:39

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 anything

@Jon Skeet 2009-02-06 08:38:38

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

@Iraimbilanja 2009-02-06 10:20:16

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.

@Jon Skeet 2009-02-06 11:00:42

@Iraimbilanja: At that point it all becomes language and platform specific, I'd say.

@Geek 2013-09-07 07:49:28

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

@Jon Skeet 2013-09-07 08:01:41

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

@Amir Bareket 2014-04-10 14:09:13

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.

@Jon Skeet 2014-04-10 14:11:13

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

@Amir Bareket 2014-04-10 14:25:06

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.

@Jon Skeet 2014-04-10 14:27:57

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

@Amir Bareket 2014-04-10 15:17:32

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

@Jon Skeet 2014-04-10 15:42:20

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

@Amir Bareket 2014-04-10 15:59:21

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

@Jon Skeet 2014-04-10 16:01:47

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

@Amir Bareket 2014-04-13 13:14:26

@Jon Skeet: Check my answer below with example for why using singleton over static is better from testing perspective. It is based on the fact that singleton can implement interfaces and static doesn’t.

@nopole 2015-12-30 17:54:29

or what about several singletons as several system resources, so you can have an array of these singleton objects, and loop through them and invoke it resource.shutdown()... is it true that in C++ or Java, a class cannot be put inside an array...? In Ruby, it can be an array of Class objects

@Jon Skeet 2015-12-30 18:20:50

@太極者無極而生L I really don't understand what you mean here, I'm afraid... your question isn't clear enough, and should probably be asked as a separate question.

@nanosoft 2016-05-09 13:20:33

In the question static class mean nested static class and not a class with only static methods. BTW if a class has only static methods then why will you instantiate it and if you want to instantiate then who is stopping you from creating 2nd, 3rd, 4th,... etc of its instances. But for singleton only one instance has to created. For nested static class check stackoverflow.com/a/37114702/1406510

@Jon Skeet 2016-05-09 13:22:58

@nanosoft: The question doesn't specify a language - you seem to be assuming it's talking about Java. My answer tries to be language neutral - although these days this question would have been closed for being unclear.

@Chatatata 2016-07-15 16:37:48

Note that C++11 entities ought to be thread-safe (from compiler aspect).

@Jon Skeet 2017-05-19 00:37:13

@KyleDelaney: I'd be surprised to see any significant difference either way.

@shaijut 2018-04-23 13:05:19

Here is good post , Static objects are stored in stack , so it should be faster than Singleton which is stored in heap ?

@Jon Skeet 2018-04-23 15:47:00

@stom: "Static objects are stored in stack" a) there's no such thing as a static object; b) all static fields are on the heap.

@Novaterata 2018-10-22 14:57:21

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 example

@Jesse Williams 2018-12-08 17:30:06

Making a threadsafe Singleton is fairly easy, and very useful, though. gist.github.com/xepherys/34d3d5ce3f44749e8649a25b38127347

@TakeMeAsAGuest 2019-03-01 16:43:12

I want to add something about multi-threading concurrency. you can atomically update Singleton reference and you never see partially constructed object, while with static fields you update fields one by one.

@cowlinator 2019-07-24 19:14:52

So, what you're saying is... if you don't have an interface to implement, always choose static, as the singleton is useless.

@Jon Skeet 2019-07-25 05:51:30

@cowlinator: I hesitate to say "always". For example, you might have in mind that you want to add an interface later, or that at some point it might go from "a singleton" to "a limited set of values". But that's at least the first thing to think about, IMO.

@Vadluri Sreenu 2012-09-11 10:22:53

  1. Singleton objects are stored in Heap, but static objects are stored in stack.
  2. We can clone (if the designer did not disallow it) the singleton object, but we can not clone the static class object .
  3. Singleton classes follow the OOP (object oriented principles), static classes do not.
  4. We can implement an interface with a Singleton class, but a class's static methods (or e.g. a C# static class) cannot.

@Alexander Yancharuk 2013-09-27 07:01:24

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.

@AgilePro 2013-10-20 18:52:02

This is answer is not correct for Java: neither the singleton nor the static uses the stack.

@Casey 2014-03-05 14:49:17

#1 is not important. #2 describes a defective implementation. #3 is completely unjustifiable.

@Renjith 2014-04-02 05:03:04

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

@Vil 2014-05-07 00:31:00

#1 stack provides faster retrieve. It might be important in some cases.

@mike_m 2014-06-08 10:36:56

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.

@Pytry 2014-10-28 14:04:21

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.

@user454322 2014-11-04 11:09:53

Continuing with Mar 5 at 14:49 @emodendroket comment: #4 Proves false in Objective-C

@Matthias Müller 2015-03-10 18:42:11

Isn't a Static Class just on the Loader Heap,so the Heap, which doesn't get checked by the GC?

@Nir Friedman 2015-05-11 22:11:13

A singleton may or may not be on the stack, it depends on how its implemented (in c++).

@Pauls 2015-08-19 10:16:08

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.

@Luis Gouveia 2015-11-12 15:44:36

This is answer is not correct for C#: Static classes are stored in the High Frequency Heap

@Groo 2016-04-28 07:05:46

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.

@nanosoft 2016-05-09 10:33:44

static class can implement interface, I could compile it.

@abhishek ringsia 2016-06-02 09:53:33

static object does not get store in stack explained in this article stackoverflow.com/questions/8387989/…

@Adowrath 2017-03-09 11:57:36

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

@nanosoft 2017-03-14 09:32:33

@Adowrath : 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.

@Adowrath 2017-03-14 10:13:13

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

@nanosoft 2017-03-14 13:12:37

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

@Adowrath 2017-03-14 16:32:51

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

@RBT 2018-01-25 00:34:03

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.

@Ajay 2018-01-25 05:54:12

All 4 justifications are plain hogwash.

@rommex 2018-06-05 05:56:18

@ΕГИІИО if you watch the sessions from WWDC 2017 on performance you will notice that it does matter, at least for iOS

@Neeraj Singh Chouhan 2020-01-13 09:47:45

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.

@Sanjay Dwivedi 2016-10-18 18:58:58

  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.

@Aaron Franke 2019-11-20 23:03:45

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?

@Rick O'Shea 2016-08-16 20:31:03

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.

@user2604650 2013-11-13 10:56:37

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

@Noctis 2014-07-30 04:53:06

I would brush it up for english grammar, but otherwise, it is an interesting read :)

@gnasher729 2014-03-31 13:33:47

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.

@nanosoft 2016-05-09 10:47:46

So if application exits will Singleton still remain in memory?

@Tom Brito 2016-05-19 19:28:56

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.

@nanosoft 2016-05-09 11:31:54

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;
        }

    }

@StriplingWarrior 2016-05-09 16:10:11

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

@nanosoft 2016-05-10 12:15:57

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

@StriplingWarrior 2016-05-10 17:26:18

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.

@nanosoft 2016-05-12 17:58:30

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?

@StriplingWarrior 2016-05-12 19:51:21

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?

@Alessandro Ornano 2016-02-11 15:08:00

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

@nopole 2015-12-30 21:05:30

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.

@RajeshVerma 2015-06-01 11:42:12

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. Static Class cannot have constructor.

  4. We cannot pass the static class to method.

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

  6. A class having all static methods.

  7. 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. Singleton class can have constructor.

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

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

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

  7. Methods can be overridden.

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

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

@Tomer Arazy 2016-06-09 17:21:32

Static classes do have constructors: msdn.microsoft.com/en-us/library/k9x6w0hc.aspx

@rahulmr 2017-01-06 15:24:27

Yes, static can have constructor which is internal to that class. This gets invoked when any static method in the class is called.

@Luminous_Dev 2017-10-29 00:33:21

For singleton on compile time, it is stored in the HEAP memory but if it gets instantiated once does it get stored in STACK?

@RBT 2018-01-23 02:32:40

@Luminous_Dev No. Any singleton instance is an object instance at the end of the day. It will get stored on heap without doubt.

@CoolOppo 2018-12-18 11:37:43

@rahulmr Important distinction: the constructor also gets invoked before the first (AKA only) instance is created.

@shelbypereira 2019-09-10 13:30:34

seems to be the most complete answer, for point 3 Static Class: I would add cannot have destructor or Finalizer

@Arpit Khandelwal 2014-08-04 06:23:08

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.

@Amir Bareket 2014-04-13 12:55:41

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.

@Jon Skeet 2014-04-13 13:22:42

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.

@Amir Bareket 2014-04-13 20:50:49

thanks for the feedback. it is very simple to make it thread safe. in addition ,i use singleton for caching purpose.

@Jon Skeet 2014-04-13 20:51:45

Yes, although with pointless overhead. Again, it's just simpler not to use a singleton.

@Vivek Vermani 2014-01-14 17:46:10

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.

@developer747 2013-06-09 23:49:01

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();
    }
}

@Sab 2013-05-24 23:58:47

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.

@Mike Rylander 2012-12-20 21:53:11

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.

@Ellen Spertus 2014-02-12 16:39:58

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?

@Mike Rylander 2014-02-13 17:59:10

@espertus Why cant you mock your singleton? Example using mockito MySingleton mockOfMySingleton = mock(MySingleton.class).

@Ellen Spertus 2014-02-13 18:34:32

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.

@Mike Rylander 2014-02-13 18:49:15

@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);

@Ellen Spertus 2014-02-13 21:13:39

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: stackoverflow.com/questions/2302179/mocking-a-singleton-clas‌​s stackoverflow.com/questions/15939023/…

@Mike Rylander 2014-02-14 00:02:35

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

@Ellen Spertus 2014-02-14 00:52:11

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.

@Eranga Dissanayaka 2012-06-27 14:03:25

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.

@RK_Muddala 2012-06-27 09:58:38

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

@Chris 2012-06-07 01:07:22

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.

@Lev 2012-05-27 22:42:38

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.

@Tilak 2012-05-08 16:34:31

  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)

@nanosoft 2016-05-09 10:43:54

Nested static class can very much implement interface in java. Your second point is Wrong.

@Petruza 2009-08-16 15:54:22

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.

@user289463 2012-02-09 14:14:44

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

@Alex 2011-08-08 03:36:34

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.

Related Questions

Sponsored Content

20 Answered Questions

[SOLVED] C++ Singleton design pattern

22 Answered Questions

[SOLVED] Creating a singleton in Python

25 Answered Questions

[SOLVED] What is the difference between MVC and MVVM?

30 Answered Questions

[SOLVED] Using a dispatch_once singleton model in Swift

18 Answered Questions

[SOLVED] Are static class variables possible in Python?

24 Answered Questions

[SOLVED] What are MVP and MVC and what is the difference?

16 Answered Questions

Sponsored Content