0

Consider the following implementation

public enum Singleton {

    INSTANCE;
    private final OnlyOne onlyOne;

    Singleton() {
        onlyOne = new OnlyOne();
    }

    public static Singleton getInstance() {
        return INSTANCE;
    }

    public static void main(String[] args) {

        Singleton one = getInstance();
        one.onlyOne.method();
    }

}

class OnlyOne {

    public void method() {
        System.out.println("Hello World");
    }
}

Here I have tried to implement the Singleton using enum. I want OnlyOne to have just one instance. My question is how do I restrict clients from instantiating objects of class OnlyOne? Because in some other class we can easily do this

OnlyOne  one = new OnlyOne();

I cannot provide a private constructor for it because doing so will break this

Singleton() {
  onlyOne = new OnlyOne();
}

Do I need to use the enum as an inner member of OnlyOne class ? Any suggestions?

4

1 回答 1

3

INSTANCE 本身就是单例。将您的方法直接添加到枚举中。

public static void main(String[] args) {
    Singleton.INSTANCE.method();
}

public enum Singleton {
    INSTANCE;
    public void method() {
        System.out.println(this);
    }
}
于 2013-11-11T04:39:08.450 回答