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 wan开发者_如何学JAVAt 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?
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.
All enum
constants are accessible. For instance through deserialisation or the enum
-specific reflective methods.
As always, I strongly suggest avoiding singletons.
精彩评论