I found few of the difference between Enum and Singleton class but not fully convinced whether Enum can be used in place of Singleton or not.
And if it can be used then what is the need of defining singleton class?
I found few of the difference between Enum and Singleton class but not fully convinced whether Enum can be used in place of Singleton or not.
And if it can be used then what is the need of defining singleton class?
An enum makes sure you have a predefined set of instances and that no further instances can be created.
A singleton makes sure that you have just one single instance.
In this sense, you could picture a Singleton as an enum with just one element.
But there are many more differences (both technical and from a design point of view) between enums and Singletons (or classes in general).
As you are asking why even use a Singleton instead of enum: One reason can be that Singletons can be 'lazy loaded', while enums can't.
Enum: The Enum in Java is a data type which contains a fixed set of constants.
The Java enum constants are static and final implicitly. It is available since JDK 1.5. To create an enum, use the enum keyword (instead of class or interface), and separate the constants with a comma. Enum declaration can be done outside a Class or inside a Class but not inside a Method.
According to Java naming conventions, it is recommended that we name constant with all capital letters
// A simple enum example where enum is declared
// outside any class (Note enum keyword instead of
// class keyword)
enum Color
{
RED, GREEN, BLUE;
}
public class Test
{
// Driver method
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1);
}
}
/////////////////////////////////////////////////////////////////
SingletonClass: In object-oriented programming, a singleton class is a class that can have only one object (an instance of the class) at a time. After first time, if we try to instantiate the Singleton class, the new variable also points to the first instance created.
public class Singleton {
private static Singleton singleton = new Singleton( );
/* A private Constructor prevents any other
* class from instantiating.
*/
private Singleton() { }
/* Static 'instance' method */
public static Singleton getInstance( ) {
return singleton;
}
/* Other methods protected by singleton-ness */
protected static void demoMethod( ) {
System.out.println("demoMethod for singleton");
}
}