枚举和单例 - 顶级vs嵌套枚举 [英] enum and singletons - top level vs nested enum

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

问题描述

现在众所周知,在java中创建单例的推荐方法是通过一个枚举(参见例如



但是(例如在这个 answer )似乎被认为是(由@MikeAdler在评论中回复我的)正确的事情有枚举 单例类中(例如,参见此处获取完整示例,或下面给出的代码)。我似乎没有真正了解这个需要/使用 - 有人可以详细说明(最好给出这个成语的正确方言)?

  public class包含{

private Enclosing(){}

static enum Singleton {
INSTANCE;

private static final Enclosing singleton = new Enclosing();

public Enclosing getSingleton(){
return singleton;
}
}
}

编辑:单例由 Enclosing.Singleton.INSTANCE.getSingleton();

解决方案

当您想执行延迟加载时,您将嵌套一个Singleton,就测试原因而言:

  public class Singleton {
public Enclosing getInstance(){
return SingletonHolder.INSTANCE;
}

static enum SingletonHolder {
INSTANCE;
}
}

在此阅读更多信息: http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom


As is now well known the recommended way for creating a singleton in java is via an enum (see for instance here)

But (for example in this answer) it seems to be considered (by @MikeAdler who replied to me in the comments) the right thing to have the enum in the singleton class (see for instance here for a full example, or the code given below). I do not seem to really understand the need/use of this - can someone please elaborate (and preferably give the correct dialect for this idiom) ?

public class Enclosing {

    private  Enclosing() {}

    static enum Singleton {
        INSTANCE;

        private static final Enclosing  singleton = new Enclosing();

        public Enclosing getSingleton() {
            return singleton;
        }
    }
}

EDIT : one would get the singleton by Enclosing.Singleton.INSTANCE.getSingleton();

解决方案

You would nest a Singleton when you wanted to perform lazy-loading of it, say for testing reasons:

public class Singleton {
    public Enclosing getInstance() {
        return SingletonHolder.INSTANCE;
    }

    static enum SingletonHolder {
        INSTANCE;
    }
}

Read more about it here: http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom

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

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