Which two are true about Singletons?

Which two are true about Singletons?

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.



Leave a Reply 9

Your email address will not be published. Required fields are marked *


Serg

Serg

I think correct is : C, E

getInstans is a Factory method

hieu

hieu

yes! act C and E

amir

amir

Singleton has only the default private constructor.

GoodLuck

GoodLuck

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.