问题
Say you have an enum singleton:
public enum Elvis {
INSTANCE;
private int age;
private Elvis() { age = 42; }
public int getAge() { return age; }
public void leaveTheBuilding() { System.out.println("I'm outta here."); }
}
Question: how do you then use it? Is it like this:
int a = Elvis.INSTANCE.getAge();
Elvis.INSTANCE.leaveTheBuilding();
// and so on, using Elvis.INSTANCE
or is it preferable to instantiate it "explicitly" and then use that instance, like so:
Elvis elvis = Elvis.INSTANCE;
int a = elvis.getAge();
elvis.leaveTheBuilding();
// and so on, using elvis
I'm tempted to use the latter to avoid having the ugly .INSTANCE
notation everywhere. But is there a drawback to doing that? (Aside from the one extra line of code to instantiate.)
回答1:
It doesn't matter. One uses a local variable, and the other doesn't. Use what you find the most readable.
回答2:
It seems to me, that you can better use a static class in this case:
public class Elvis {
private static int age = 42;
private Elvis() {}
public static int getAge() { return age; }
public static void leaveTheBuilding() {
System.out.println("I'm outta here.");
}
}
And then do:
int a = Elvis.getAge();
Elvis.leaveTheBuilding();
// etc.
来源:https://stackoverflow.com/questions/8758558/instantiating-and-using-an-enum-singleton