You want to create a singleton class by using the Singleton design pattern.

Which two statements enforce the singleton nature of the design?

A. Make the class static.
B. Make the constructor private.
C. Override equals() and hashCode() methods of the java.lang.Object class.
D. Use a static reference to point to the single instance.
E. Implement the Serializable interface.

題解

Singleton design pattern 能保證一個類別只能有一個物件實體。

選項 A,靜態類別和它能產生多少個實體並沒有關聯。

選項 B,用 private 來修飾建構子,可以有效地阻絕外部類別任意實體化出物件實體。

選項 C,equals 和 hashCode 方法和物件實體化沒有什麼關聯。

選項 D,用靜態的變數來儲存第一次實體化出來的物件參考,接下來都返回這個物件參考即可。

選項 E,Serializable 和實體化沒有什麼關聯。