Singleton classes - java

Is there any difference between a Singleton class and a class with
all static members (i.e. methods and attributes).
I could not find any instance where 'all static member class' would not achieve
the same functionality as class properly implementing Singleton pattern?
For eg. java.lang.Runtime is a proper Singleton class whereas java.lang.System has all static method for access and merely has a private constructor to avoid external construction . Does anybody know why classes like Runtime are made Singleton and not implemented like java.lang.System.
Is it merely because it would be a cleaner design (i.e. mimics an object more realistically) or is there some performance benefit here?

Yes, there's a difference - a singleton can implement an interface.
Also, what looks like a singleton from the outside can actually be implemented via different classes, where the singleton access method (e.g. Runtime.getRuntime()) can create the right instance at execution time. I'm not saying that's what's happened here, but it's an option.

Well you can serialize and unserialize an object (and thus a Singleton) using the Serializable interface (on Java), but not a static class.

A singleton is instantiated once.
A static class is never instantiated.

I believe there is no difference between what you call a singleton and a class with all static methods/members in principle. In fact, I think that creating a class with all static members is a way of implementing the singleton idiom. Well, maybe in Java there is some kind of serious difference, but I'm speaking from the C++ point of view.

I think you should ask what's different between final class with private constructor and static class.
Because singleton is a class and implementation depends on programmer who programs this class.
It's same as ask what's differences between an object and static class.

A class can be extended to create another singleton (e.g. for testing purposes), or non-singleton class. static methods cannot be overidden, they can only be hidden in a sub class.

A common use for singletons with lazy initialization (aka Meyers singletons) is to control the order of static objects initialization (which, in C++, is undefined across different translation units). In this respect, singletons just behave like global objects, but whose order of construction behaves well.
It becomes quite difficult to control the order of destruction though. If you must rely on the singletons being destructed in some particular order (eg. a singleton logging class which should outlast other singleton instances), see Alexandrescu's book to witness the difficulty.

The primary purpose for singletons cited by the GoF is to provide a polymorphic service, where the singleton is an abstract base class, and the concrete type is decided at runtime. And, of course, there must only be one of them in the program.

Related

What is the use of the enum singleton in Java?

When the Gang of four introduced the singleton pattern, they also had to explain, why not to use static class fields and method instead. The reason was: the possibility to inherit. For Java it had sense - we cannot normally inherit the class fields and methods.
Later the "Effective Java" book appeared. And we know now that the existence of reflection destroys the singularity of the singleton class with private constructor. And the only way to make a real SINGLEton is to make it as a single item of an enumeration. Nice. I had done some myself this way.
But a question remains: While we cannot inherit from enumeration, what is the use of this singleton? Why we don't use these old good static/class fields and methods?
Edit. Thanks to the #bayou.io I see that in https://softwareengineering.stackexchange.com/a/204181/44104 there is a code that can trick the enum, too, and create again two exemplars of the enum singleton. The other problems are mentioned there, too. So, there is no need to use enum instead of the usual singleton class pattern, too? BTW, all enum pluses that are mentioned here till now, work for singleton classes, too.
what is the use of this singleton? Why we don't use these old good static/class fields and methods?
Because enum is an object so it can not only be passed around but also implement interfaces.
Also since we are making a class, we can use the different public/private options available to all kinds of classes.
So in practice, we can make a singleton that implements an interface and then pass it around in our code and the calling code is non the wiser. We can also make the enum class package private but still pass it around to other classes in other packages that expect the interface.
If we used the static methods version, then the calling class would have to know that this object is a singleton, and our singleton class would have to be public so the other classes can see it and use it's methods.
There's nothing particularly wrong with the "good old fashioned singleton", enum "singletons" are just convenient - it saves you the need to muck around with boiler-plated code that looks the same in every singelton.
To me, a singleton makes sense wherever you want to represent something which is unique in its kind.
As an example, if we wanted to model the Sun, it could not be a normal class, because there is only one Sun. However it makes sense to make it inherit from a Star class. In this case I would opt for a static instance, with a static getter.
To clarify, here is what I'm talking about :
public class Star {
private final String name;
private final double density, massInKg;
public Star(String name, double density, double massInKg) {
// ...
}
public void explode() {
// ...
}
}
public final class Sun extends Star {
public static final Sun INSTANCE = new Sun();
private Sun() { super("The shiniest of all", /**...**/, /**...**/); }
}
Sun can use all the methods of Star and define new ones. This would not be possible with an enum (extending a class, I mean).
If there is no need to model this kind of inheritance relationships, as you said, the enum becomes better suited, or at least easier and clearer. For example, if an application has a single ApplicationContext per JVM, it makes sense to have it as a singleton and it usually doesn't require to inherit from anything or to be extendable. I would then use an enum.
Note that in some languages such as Scala, there is a special keyword for singletons (object) which not only enables to easily define singletons but also completely replaces the notion of static method or field.
ENUM singletons are easy to write. It will occupy very less code, which is clean & elegant if you compare with implementation of lazy singleton with double synchronized blocks
public enum EasySingleton{
INSTANCE;
}
Creation of ENUM instance is thread safe.
ENUM singletons handled serialization by themselves.
conventional Singletons implementing Serializable interface are no longer remain Singleton because readObject() method always return a new instance just like constructor in Java. you can avoid that by using readResolve() method and discarding newly created instance by replacing with Singeton
private Object readResolve(){
return INSTANCE;
}
Have a look at this article on singleton

Is a static class a singleton? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Difference between static class and singleton pattern?
I was wondering,
Would a class such as Java's Math class, where all methods are static be considered a singleton? Or does a singleton have to have an instance, eg: Math.getInstance().abs(...) to qualify as a singleton?
Thanks
Having just static methods in a class does not qualify it being a Singleton, as you can still make as many instances of that class, if you have a public constructor in it.
For a class to qualify as Singleton, it should have private constructor, so that it can't be instantiated from outside the class, and have a static factory that returns the same instance everytime invoked.
If you really mean static class, then first of all, you can't have your top-level class as static. You can only have static nested class, in which case you don't need to create any instance of that class, but you can and you can create multiple instances and hence it as not Singleton.
Also, the class you mentioned - java.lang.Math, is not a static class. You should see the documentation of that.
Static classes in Java are just nested classes which aren't inner classes. (They're not like static classes in C#, for example.) They can still have instance methods, state etc - and there can be multiple instances.
java.lang.Math is not a static class.
And no, a class which never has an instance is not a singleton. The important difference is that a singleton can implement an interface (or even derive from an abstract class) whereas if you never create an instance of a class, any instance methods are pointless.
A class that is applied Singleton Pattern has one or none instance at any time on a JVM. That's why it's called single-ton. Having static or non-static members has no relationship with being singleton or non-singleton.
Static classes usually provide some helper methods. In fact i don't think its appropriate to compare Static classes with Singleton. Both are completely different.
We can create multiple instances of a static class but singleton guarantees(atleast in theory) only single instance.
It would have to have an instance with Singleton meaning to only be initialised, once.
Edit: Here's a link to the Wikipedia article
A singleton guarantees that there is only up to one instance of that class within the environment. It is different from a class with a bunch of static methods. A singleton carries state and can carry runtime values, while static methods of a class don't.
You can argue that you can have static values to do that, but the purpose of static variables is different (and sometimes abused like global variables). So a singleton operates in a different context than static methods.
A singleton also is usually associated with some resource (some connection to another server, access to some file, etc.) for which a static instance wouldn't be that ideal. Singletons also allow for lazy loading (if connecting or accessing a resource is expensive), while classes get loaded when the classloader encounters a reference to them.

Should I use a pool of objects, a singleton or static methods in a multi-threaded environment?

I have a helper class that creates some objects, like a builder. The helper class does not have a state. It is on a multi-threaded environment; specifically, a web server. Is this class a good candidate for being a singleton?
What would be the difference between implementing this class as a singleton and just using static methods?
What would the effect of thousands of users accessing this object/these methods be?
I could make the class a regular class, but instantiating it every time it is needed would be a waste of memory.
Infact instead of singleton you can make the methods static.
Singleton doesn't have to be only 1, you can create a pool of instances and delegate work depending on the requirement, where as you don't have such control with static methods.
discussion on Singleton vs Static methods is here
As the name suggests, singletons are used to have only one instance of the object present at the time. So singleton does have a state, but you're accessing to that one state wherever you're calling your singleton.
So if you don't need any state saved in your class/method I'd suggest to use static approach.
No need to use singleton here (since you do not need a state), you can use static methods.
Singleton in principle offers more control by allowing a state. There won't be much difference in your case, but static methods will be easier to implement and use.
What would the effect of thousands of users accessing this object/these methods be?
Again, not much difference in both cases, but in Singleton you can have a state, and if you do not implement carefully, your code will be non-thread-safe. Every user calling the static method gets its own "instance" of the method (I think this is what you ask), so no risk of running into thread-safety problems there.
As has been stated before, given that your class doesn't have object state, static methods would work just fine.
However, consider the following - Depending on the overall design of your system, you may want to be able to specify a different implementation of the methods. This is usually done with either subclassing (...), or interface implementation (now the preferred method) - look up the strategy pattern. In either case, being able to provide alternte implementations would require you to not use static methods, but to have an (empty) object to call methods on.

static class vs singleton class

I know this topic has been discussed and killed over and over again, but I still had one doubt which I was hoping someone could help me with or guide me to a pre-existing post on SO.
In traditional C, static variables are stored in data segments and local variables are stored in the stack. Which I would assume will make static variables more expensive to store and maintain when compared to local variables. Right?
When trying to understand in terms of Java or C#, would this be dis-advantage for static classes when compared to singleton class? Since the entire class is loaded into memory before class initialization, I don't see how it can be an advantage unless we have small inline-able functions.
I love Singleton classes, and would hate to see it become an anti-pattern, I am still looking for all the advantages that come with it...and then loose to the argument of thread-safety among others.
-Ivar
Different from C, the static keyword in Java class definition merely means, This is just a normal class like any other class, but it just happens to be declared inside another class to organize the code. In other words, there is no behavioral difference whatsoever between the following 2 way of declaration*:
a)
class SomeOtherClass {
static class Me {
// If you "upgrade" me to a top-level class....
}
}
b)
class Me {
// I won't behave any different....
}
Class definitions are loaded to memory when the class is used for the first time, and this is true for both "static" and "non-static" classes. There are no difference in how memory will be used, either. In older JVMs, objects were always stored in heap. Modern JVMs do allocate objects on stack when that is possible and beneficial, but this optimization is transparent to the coder (it is not possible to influence this behavior via code), and use of the static keyword does not have any effect on this behavior.
Now, back to your original question, as we have seen we really can't compare static classes and Singleton in Java as they are completely different concept in Java (I'm also not sure how static classes would compare with Singleton, but I will focus on Java in this answer). The static keyword in Java is overloaded and has many meanings, so it can be confusing.
Is Singleton automatically an "anti-pattern"? I don't think so. Abuse of Singleton is, but the Singleton pattern itself can have many good uses. It just happens to be abused a lot. If you have legitimate reason to use the Singleton pattern, there is nothing wrong in using it.
*Note: Why write static at all, you might ask. It turns out "non-static" nested classes have their own somewhat complicated memory management implication, and its use is generally discouraged unless you have a good reason (pls refer to other questions for more info).
class SomeOtherClass {
Stuff stuff;
class Me {
void method(){
// I can access the instance variables of the outer instance
// like this:
System.out.println(SomeOtherClass.this.stuff);
// Just avoid using a non-static nested class unless you
// understand what its use is!
}
}
}
Singleton class is essentially a regular top-level class with a private constructor, to guarantee its singleness. Singleton class itself provides a way to grab its instance. Singleton classes are not very easy to test, therefore we tend to stick with the idea of Just Create Once.
static class is essentially a nested class. A nested class is essentially a outer level class which is nested in another class just for packaging convenience. A top-level class can not be declared as static, in Java at least -- you should try it yourself.
would this be dis-advantage for static
classes when compared to singleton
class?
Your this question became somewhat invalid now, according to the above explanation. Furthermore, a static class (of course nested) can also be a singleton.
Further reading:
Inner class in interface vs in class
The differences between one and the other is the memory management, if your app will have to instantiate a lot of things, that will burn the memory like a charm becoming a memory problem, performance and other things...
this could help...
http://butunclebob.com/ArticleS.UncleBob.SingletonVsJustCreateOne
http://www.objectmentor.com/resources/articles/SingletonAndMonostate.pdf
I'm afraid it is an anti-pattern:
http://thetechcandy.wordpress.com/2009/12/02/singletons-is-anti-pattern/

Why use a singleton instead of static methods?

I have never found good answers to these simple questions about helper/utility classes:
Why would I create a singleton (stateless) instead of using static methods?
Why would an object instance be needed if an object has no state?
Often, singletons are used to introduce some kind of global state to an application. (More often than really necessary, to be honest, but that's a topic for another time.)
However, there are a few corner cases where even a stateless singleton can be useful:
You expect to extend it with state in the foreseeable future.
You need an object instance for some particular technical reason. Example: Synchonization objects for the C# lock or the Java synchronized statement.
You need inheritance, i.e., you want to be able to easily replace your singleton with another one using the same interface but a different implementation.Example: The Toolkit.getDefaultToolkit() method in Java will return a singleton whose exact type is system dependent.
You want reference equality for a sentinel value.Example: DBNull.Value in C#.
I could see a case for a stateless singleton being used instead of a static methods class, namely for Dependency Injection.
If you have a helper class of utility functions that you're using directly, it creates a hidden dependency; you have no control over who can use it, or where. Injecting that same helper class via a stateless singleton instance lets you control where and how it's being used, and replace it / mock it / etc. when you need to.
Making it a singleton instance simply ensures that you're not allocating any more objects of the type than necessary (since you only ever need one).
Actually i've found another answer not mentionned here: static methods are harder to test.
It seems most test frameworks work great for mocking instance methods but many of them no not handle in a decent way the mock of static methods.
In most programming languages classes elude a lot of the type system. While a class, with its static methods and variables is an object, it very often cannot implement an interface or extend other classes. For that reason, it cannot be used in a polymorphic manner, since it cannot be the subtype of another type. For example, if you have an interface IFooable, that is required by several method signatures of other classes, the class object StaticFoo cannot be used in place of IFooable, whereas FooSingleton.getInstance() can (assuming, FooSingleton implements IFooable).
Please note, that, as I commented on Heinzi's answer, a singleton is a pattern to control instantiation. It replaces new Class() with Class.getInstance(), which gives the author of Class more control over instances, which he can use to prevent the creation of unneccessary instances. The singleton is just a very special case of the factory pattern and should be treated as such. Common use makes it rather the special case of global registries, which often ends up bad, because global registries should not be used just willy-nilly.
If you plan to provide global helper functions, then static methods will work just fine. The class will not act as class, but rather just as a namespace. I suggest, you preserve high cohesion, or you might end up with weirdest coupling issues.
greetz
back2dos
There is a trade-off between using which one. Singletons may or may not have state and they refer to objects. If they are not keeping state and only used for global access, then static is better as these methods will be faster. But if you want to utilize objects and OOP concepts (Inheritance polymorphism), then singleton is better.
Consider an example: java.lang.Runtime is a singleton class in java. This class allows different implementations for each JVM. The implementation is single per JVM. If this class would have been static, we cannot pass different implementations based on JVM.
I found this link really helpful: http://javarevisited.blogspot.com/2013/03/difference-between-singleton-pattern-vs-static-class-java.html?
Hope it helps!!
Singleton is not stateless, it holds the global state.
Some reasons which I can think of using Singleton are:
To avoid memory leaks
To provide the same state for all modules in an application e.g database connection
For me "Want Object State use Singleton, Want Function use static method"
It depends on what you want. Whenever you want the object state (e.g. Polymorphism like Null state instead of null, or default state), singleton is the appropriate choice for you whereas the static method use when you need function (Receive inputs then return an output).
I recommend for the singleton case, it should be always the same state after it is instantiated. It should neither be clonable, nor receive any value to set into (except static configuration from the file e.g. properties file in java).
P.S. The performance between these 2 are different in milliseconds, so focus on Architecture first.
According to GoF’s book Design Patterns, chapter ‘Singleton’, class operations have the following drawbacks compared to singletons (bold emphasis mine):
More flexible than class operations. Another way to package singleton’s functionality is to use class operations (that is, static member functions in C++ or class methods in Smalltalk). But both of these language techniques make it hard to change a design to allow more than one instance of a class. Moreover, static member functions in C++ are never virtual, so subclasses can’t override them polymorphically.

Categories