patternjavaMajor
Singleton using enum
Viewed 0 times
enumsingletonusing
Problem
Is this the correct implementation of a singleton using enum?
public class Item3 {
public static void main(String[] args) {
Singleton s=Singleton.Single.INSTANCE.getInstance();
Singleton s2=Singleton.Single.INSTANCE.getInstance();
System.out.printf("%b",s==s2);
}
}
class Singleton {
enum Single{
INSTANCE;
Singleton s=new Singleton();
public Singleton getInstance(){
if(s==null)
return new Singleton();
else return s;
}
}
}Solution
No, it is simpler to code than that:
Then you use can use
And NEVER do that:
this is not thread safe! What is more, the
enum Singleton
{
INSTANCE;
// instance vars, constructor
private final Connection connection;
Singleton()
{
// Initialize the connection
connection = DB.getConnection();
}
// Static getter
public static Singleton getInstance()
{
return INSTANCE;
}
public Connection getConnection()
{
return connection;
}
}Then you use can use
final Singleton s = Singleton.getInstance(). Note however that since this is an enum you can always access this via Singleton.INSTANCE.And NEVER do that:
public Singleton getInstance(){
if(s==null)
return new Singleton();
else return s;
}this is not thread safe! What is more, the
new Singleton() value is never assigned to s... (thanks @DaveJarvis for noticing this!)Code Snippets
enum Singleton
{
INSTANCE;
// instance vars, constructor
private final Connection connection;
Singleton()
{
// Initialize the connection
connection = DB.getConnection();
}
// Static getter
public static Singleton getInstance()
{
return INSTANCE;
}
public Connection getConnection()
{
return connection;
}
}public Singleton getInstance(){
if(s==null)
return new Singleton();
else return s;
}Context
StackExchange Code Review Q#27296, answer score: 27
Revisions (0)
No revisions yet.