将枚举INSTANCE设为私有

jax*_*jax 6 java singleton enums private

我正在使用这样的enum singletom模式:

public enum LicenseLoader implements ClientLicense {
    INSTANCE;

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

   ...rest of code

}
Run Code Online (Sandbox Code Playgroud)

现在我想返回接口并隐藏我们实际上正在使用枚举的事实.我希望客户端使用getInstance()而不是LicenseLoader.INSTANCE,因为有一天我可能会决定使用不同的模式.

是否可以将INSTANCE私有化为枚举?

pol*_*nts 4

public interface制作一个带有private enumimplements例常量的接口怎么样INSTANCE

所以,像这样(为简洁起见,全部集中在一个类中):

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

这样,您就不会暴露Elvis.INSTANCE(甚至enum Elvis根本不会)使用interface来定义您的功能,隐藏所有实现细节。