实例化和使用枚举单例 [英] Instantiating and using an enum singleton

查看:139
本文介绍了实例化和使用枚举单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有一个枚举单例:

  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。); }
}

问题:你怎么使用它?是这样的:

  int a = Elvis.INSTANCE.getAge(); 
Elvis.INSTANCE.leaveTheBuilding();
//等等,使用Elvis.INSTANCE

或者最好实例化明确,然后使用该实例,如下所示:

  Elvis elvis = Elvis.INSTANCE; 
int a = elvis.getAge();
elvis.leaveTheBuilding();
//等等,使用elvis

我很想使用后者避免在任何地方出现丑化的 .INSTANCE 符号。但是这样做有缺点吗? (除了一个额外的代码行实例。)

解决方案

没关系。一个使用局部变量,另一个不使用。使用你最可读的东西。


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.)

解决方案

It doesn't matter. One uses a local variable, and the other doesn't. Use what you find the most readable.

这篇关于实例化和使用枚举单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆