Instantiating and using an enum singleton

流过昼夜 提交于 2019-12-22 11:29:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!