Singleton Pattern: Ensure that only one instance of the class exists.
Provide global access to that instance by:
- Declaring all constructors of the class to be private.
- Providing a static method that returns a reference to the instance. The lazy initialization concept is used to write the static methods.
- The instance is stored as a private static variable.
class Printer { private static Printer printer = new Printer(); private Printer() { // empty } public static Printer getPrinter() { return printer; } void takePrints() { System.out.println(“Printing…”); } } class UsePrinter { public static void main(String[] args) { Printer printer = Printer.getPrinter(); printer.takePrints(); } } |
Note: We need to synchronize takePrints() method of Printer class when multiple threads trying take prints parallel. |