C
Chris Berg
I have these options, both works fine, but I wonder which one would be
considered more 'correct':
1) // ordinary Singleton pattern
public final class MainClass{
private int something;
private MainClass instance;
private MainClass(){
-- do all initialization --
}
public static synchronized MainClass getInstance(){
if (instance==null) instance=new MainClass();
return instance;
}
public int getSomething(){
return something;
}
}
2) // static class, no instance
public final class MainClass
private static int something;
private MainClass(){} // never instantiate
static{
-- do all initialization --
}
public static int getSomething(){
return something;
}
}
Calling getSomething() is simpler in 2); in 1) I always have to obtain
the instance first, and I think a virtual method may be more expensive
in CPU time - however, 2) does not look very 'object oriented'. Of
course, in 1) the instance is an actual Object that can be treated as
such, for instance it has toString() etc, but if that is not needed,
would 2) be considered 'bad taste', and why ? Normally, you see static
methods used for utilities (i.e. java.lang.Math).
Chris
considered more 'correct':
1) // ordinary Singleton pattern
public final class MainClass{
private int something;
private MainClass instance;
private MainClass(){
-- do all initialization --
}
public static synchronized MainClass getInstance(){
if (instance==null) instance=new MainClass();
return instance;
}
public int getSomething(){
return something;
}
}
2) // static class, no instance
public final class MainClass
private static int something;
private MainClass(){} // never instantiate
static{
-- do all initialization --
}
public static int getSomething(){
return something;
}
}
Calling getSomething() is simpler in 2); in 1) I always have to obtain
the instance first, and I think a virtual method may be more expensive
in CPU time - however, 2) does not look very 'object oriented'. Of
course, in 1) the instance is an actual Object that can be treated as
such, for instance it has toString() etc, but if that is not needed,
would 2) be considered 'bad taste', and why ? Normally, you see static
methods used for utilities (i.e. java.lang.Math).
Chris