简体   繁体   中英

Enums and Singletons

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?

INSTANCE itself is the singleton. Add your method directly to the enum.

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

public enum Singleton {
    INSTANCE;
    public void method() {
        System.out.println(this);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM