Java – Singleton Pattern

Singleton Pattern: Ensure that only one instance of the class exists.

Provide global access to that instance by:

  1. Declaring all constructors of the class to be private.
  2. Providing a static method that returns a reference to the instance. The lazy initialization concept is used to write the static methods.
  3. 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.

Scroll to Top