Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make an enum INSTANCE private

I am using an enum singletom pattern like this:

public enum LicenseLoader implements ClientLicense {
    INSTANCE;

    /**
     * @return an instance of ClientLicense
     */
    public static ClientLicense getInstance() {
        return (ClientLicense)INSTANCE;
    }

   ...rest of code

}

Now I want to return the Interface and hide the fact that we are actually using an enum at all. I want the client to use getInstance() and not LicenseLoader.INSTANCE as one day I may decide to use a different pattern if necessary.

Is is possible to make INSTANCE private to the enum?

like image 688
jax Avatar asked Jul 04 '10 10:07

jax


1 Answers

What about making a public interface and private enum that implements said interface, with a singleton INSTANCE constant?

So, something like this (all in one class for brevity):

public class PrivateEnum {

    public interface Worker {
        void doSomething();
    }

    static private enum Elvis implements Worker {
        INSTANCE;
        @Override public void doSomething() {
            System.out.println("Thank you! Thank you very much!");
        }
    }

    public Worker getWorker() {
        return Elvis.INSTANCE;
    }
}

This way, you're not exposing Elvis.INSTANCE (or even enum Elvis at all), using an interface to define your functionality, hiding all implementation details.

like image 151
polygenelubricants Avatar answered Oct 03 '22 07:10

polygenelubricants