Java Design Patterns Singleton Patterns

Introduction

Singleton Patterns ensure that a class only has one instance.

It provides a global reference to it.

Use cases

  • One application can only have one main window.
  • One application wants to have one configuration manager.

Example

First we made the constructor private first, so that we cannot instantiate in normal way.

When creating an instance of the class, check whether we already have one available copy.

If we do not have any such copy, we'll create it; otherwise, we'll reuse the existing copy.

Example

class ConfigurationManager {
   private ConfigurationManager() {
   }//w w  w  . java 2  s  . c o  m

   private static class SingletonHelper {
      private static final ConfigurationManager intance = new ConfigurationManager();
   }

   public static ConfigurationManager get() {
      return SingletonHelper.intance;
   }

}

public class Main {
   public static void main(String[] args) {
      ConfigurationManager c1 = ConfigurationManager.get();
      ConfigurationManager c2 = ConfigurationManager.get();
      if (c1 == c2) {
         System.out.println("c1 and c2 are same instance");
      }

   }
}



PreviousNext

Related