How is a singleton different from a class filled with only static fields?
-
1Are you asking "what are the practical differences?"Matt Ball– Matt Ball2010-08-20 15:09:58 +00:00Commented Aug 20, 2010 at 15:09
-
i'm just curious about the general differences of the two i.e. Is there something unique about a Singleton that makes it different from a class that has all it's methods and attributes set to static?cesar– cesar2010-08-20 15:29:29 +00:00Commented Aug 20, 2010 at 15:29
-
DCL way of implementing singleton has only static field instance holding a static reference to the singleton object and then lazily instantiated in static method. In this case this Singleton implementation has only static field and methods and they are same(Not different as question asks). That's one implementation. Other can be through Enum.nanosoft– nanosoft2016-05-09 13:11:04 +00:00Commented May 9, 2016 at 13:11
12 Answers
Almost every time I write a static class, I end up wishing I had implemented it as a non-static class. Consider:
- A non-static class can be extended. Polymorphism can save a lot of repetition.
- A non-static class can implement an interface, which can come in handy when you want to separate implementation from API.
Because of these two points, non-static classes make it possible to write more reliable unit tests for items that depend on them, among other things.
A singleton pattern is only a half-step away from static classes, however. You sort of get these benefits, but if you are accessing them directly within other classes via `ClassName.Instance', you're creating an obstacle to accessing these benefits. Like ph0enix pointed out, you're much better off using a dependency injection pattern. That way, a DI framework can be told that a particular class is (or is not) a singleton. You get all the benefits of mocking, unit testing, polymorphism, and a lot more flexibility.
3 Comments
Let me sum up :)
The essential difference is: The existence form of a singleton is an object, static is not. This conduced the following things:
- Singleton can be extended. Static can't be.
- Singleton creation may not be threadsafe if it isn't implemented properly. Static is threadsafe.
- Singleton can be passed around as an object. Static can't be.
- Singleton can be garbage collected. Static can't be.
- Singleton is better than static class!
- More here that I haven't realized yet :)
Last but not least, whenever you are going to implement a singleton, please consider to redesign your idea to not use this God object (believe me, you will tend to put all the "interesting" stuff in this class) and use a normal class named "Context" or something like that instead.
5 Comments
A singleton can be initialized lazily, for one.
2 Comments
I think, significant thing is 'object' in object oriented programing. Except from few cases we should restrict to usage of static classes. That cases are:
- When the create an object is meaningless. Like methods of java.lang.Math. We can use the class like an object. Because the behavior of Math class methods doesn't depend on the state of the objects to be created in this class.
- Codes to be used jointly by more than one object method, the codes that do not reach the object's variables and are likely to be closed out can be static methods
Another important thing is singleton is extensible. Singleton can be extended. In the Math class, using final methods, the creation and extension of the object of this class has been avoided. The same is true for the java.lang.System class. However, the Runtime class is a single object, not a static method. In this case you can override the inheritance methods of the Runtime class for different purposes.
You can delay the creation of a Singleton object until it is needed (lazy loading). However, for static method classes, there is no such thing as a condition. If you reach any static member of the class, the class will be loaded into memory.
As a result, the most basic benefit to the static method class is that you do not have to create an object, but when used improperly, it will remove your code from being object-oriented.
1 Comment
Date.Now call. yet 99.99% of the time using the static Date.Now method call makes mocking tests nearly impossible. Or rather, static methods don't generally allow injection and mocking.The difference is language independent. Singleton is by definition: "Ensure a class has only one instance and provide a global point of access to it. " a class filled with only static fields is not same as singleton but perhaps in your usage scenario they provide the same functionality. But as JRL said lazy initiation is one difference.
Comments
At least you can more easily replace it by a mock or a stub for unit testing. But I am not a big fan of singletons for exactly the reason you are describing : it are global variables in disguise.
9 Comments
A singleton class will have an instance which generally is one and only one per classloader. So it can have regular methods(non static) ones and they can be invoked on that particular instance.
While a Class with only static methods, there is really no need in creating an instance(for this reason most of the people/frameworks make these kind of Util classes abstract). You will just invoke the methods on class directly.
Comments
The first thing that comes to mind is that if you want to use a class with only static methods and attributes instead of a singleton you will have to use the static initializer to properly initialise certain attributes. Example:
class NoSingleton {
static {
//initialize foo with something complex that can't be done otherwise
}
static private foo;
}
This will then execute at class load time which is probably not what you want. You have more control over this whole shebang if you implement it as a singleton. However I think using singletons is not a good idea in any case.
1 Comment
A singleton is a class with just one instance, enforced. That class may have state (yes I know static variables hold state), not all of the member variables or methods need be static.
A variation would be a small pool of these objects, which would be impossible if all of the methods were static.
2 Comments
NOTE: The examples are in C#, as that is what I am more familiar with, but the concept should apply to Java just the same.
Ignoring the debate on when it is appropriate to use Singleton objects, one primary difference that I am aware of is that a Singleton object has an instance that you can pass around.
If you use a static class, you hard-wire yourself to a particular implementation, and there's no way to alter its behavior at run-time.
Poor design using static class:
public class MyClass
{
public void SomeMethod(string filename)
{
if (File.Exists(filename))
// do something
}
}
Alternatively, you could have your constructor take in an instance of a particular interface instead. In production, you could use a Singleton implementation of that interface, but in unit tests, you can simply mock the interface and alter its behavior to satisfy your needs (making it thrown some obscure exception, for example).
public class MyClass
{
private IFileSystem m_fileSystem;
public MyClass(IFileSystem fileSystem)
{
m_fileSystem = fileSystem;
}
public void SomeMethod(string filename)
{
if (m_fileSystem.FileExists(filename))
// do something
}
}
This is not to say that static classes are ALWAYS bad, just not a great candidate for things like file systems, database connections, and other lower layer dependencies.
Comments
One of the main advantages of singletons is that you can implement interfaces and inherit from other classes. Sometimes you have a group of singletons that all provide similar functionality that you want to implement a common interface but are responsible for a different resource.
1 Comment
Singleton Class : Singleton Class is class of which only single instance can exists per classloader.
Helper Class (Class with only static fields/methods) : No instance of this class exists. Only fields and methods can be directly accessed as constants or helper methods.
These few lines from this blog describes it nicely:
Firstly the Singleton pattern is very useful if you want to create one instance of a class. For my helper class we don't really want to instantiate any copy's of the class. The reason why you shouldn't use a Singleton class is because for this helper class we don't use any variables. The singleton class would be useful if it contained a set of variables that we wanted only one set of and the methods used those variables but in our helper class we don't use any variables apart from the ones passed in (which we make final). For this reason I don't believe we want a singleton Instance because we do not want any variables and we don't want anyone instantianting this class. So if you don't want anyone instantiating the class, which is normally if you have some kind of helper/utils class then I use the what I call the static class, a class with a private constructor and only consists of Static methods without any any variables.