Skip to main content

Creational Patterns : Singleton


Properties:
-          Ensures that only one instance is created.
-          Global access is provided to single instance.
-          Conventionally has a public static method named getInstance/getXYZ ,where XYZ stands for class name, to return the class instance.
-          Suitable for creating factory instances and system wide unique resources.


Implementation:
-          Constructor should be made private/protected to prevent arbitrary instance creation.
-          Single instance is created and assigned to a public static member of the class. This class member is conventionally named as instance.
-          Class instance is exposed to outside world by a public static method named getInstance/getXYZ ,where XYZ stands for class name.


Java Standard Library Implementations:
-          java.lang.Runtime
-          java.awt.Desktop
-          java.awt.print.PrinterJob

Example Usage:
PrinterJob pj = PrinterJob.getPrinterJob();

if (pj.printDialog()) {
    try {
        pj.print();
    }
    catch (PrinterException e) {
        e.printStackTrace();
    }
 }  

Comments