I am not able to understand how Enum can be used for thread safe singleton instantiation. So let us say I have a class A which I want to make singleton. How do I do that using Enum ? I came across suggestion like the code below, but not really able to understand. In the below shall I replace INSTANCE with A singleObj = new A();
?
Moreover, how exactly should class A look like as in what thing should I take care of there .. for example: making constructor private etc.
public enum EasySingleton{
INSTANCE;
}
In the below shall I replace INSTANCE with
A singleObj = new A();
?
You don't. You use:
EasySingleton instance = EasySingleton.INSTANCE;
You write the singleton just like a normal class, with whatever methods you want etc - but no public constructors (which aren't valid in enums anyway).
As Jon mentioned you would do the following:
EasySingleton instance = EasySingleton.INSTANCE;
instance.doSomething();
If you need some further examples, as well as pros/cons to many of the approaches to creating Singleton classes you can visit: http://avaldes.com/creating-a-thread-safe-singleton-class-with-examples/ .
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.