Which two are true about Singletons?
A.
A Singleton must implement serializable.
B.
A Singleton has only the default constructor.
C.
A Singleton implements a factory method.
D.
A Singleton improves a class’s cohesion.
E.
Singletons can be designed to be thread-safe.
Explanation:
B:The Singleton Pattern is one of the commonly used design templates when there needs to be a control on how an object can be created. This design pattern proposes that at any time there can only be one instance of a singleton (object) created by the JVM. The Singleton class’s default constructor is made private, which prevents the direct instantiation of the object by others (Other Classes).
E:The singletonpattern makes unit testing far more difficult,as it introduces global state into an application. It should also be noted that this pattern reduces the potential for parallelism within a program, because access to the singleton in a multi-threaded context must be serialised, e.g., by locking.
I think correct is : C, E
getInstans is a Factory method
+1
C and E
yes! act C and E
C, E
Singleton has only the default private constructor.
The official Oracle notes mentioned about having only private constructor and having a getInstance() which is a factory method. It didn’t mention about having only the default constructor. It also mention that a factory can be missing if the “static final Instance” property is actually public. It made no mention of thread-safe. In fact, Googling around says that Singleton makes it difficult for thread-safe but it “CAN” be done.
C E
ce