Escolar Documentos
Profissional Documentos
Cultura Documentos
Example:
NutritionFacts.java
3.
c.
There are two approaches public attribute with private constructor and public factory method with private constructor.
d. The advantage of factorymethod approach is implementation details can be hidden. e. In case of a singleton class that is implementing serializable interface following additional things to be taken care. i. All the attributes should be made transient ii. Implement readResolve method and return the same instance [in the below example return INSTANCE
SingleTon.java
f.
From Java 1.5 onwards, we can use enums. i. Example: public enum SingleTon{ INSTANCE; Public getValue(){ //provide implementations. } }
The above enum approach is equivalent to public field approach. The additional benefit is, it provides the serialization machinery for free. Of all the approaches single element enum is the best way to implement a singleton. 4.
5.
6.
7.
Avoid Finalizers.
a. Finalizers are unpredictable, often dangerous, and generally un-necessary b. There is a severe performance penalty for using finalizers.