Page 1 of 1

Singleton in Java

PostPosted: 05 Mar 2019, 07:55
by Ursego
To see the keywords colored, save the following text in a text file and open it in a Java compiler (or in Notepad++ and select in the menu: Language > J > Java).

Code: Select all
// The singleton pattern is a creational pattern focused on creating only one instance of an object in memory within an application, sharable by all classes and threads within the application. The globally available object created by the singleton pattern is referred to as a singleton. Singletons may also improve performance by loading reusable data that would otherwise be time consuming to store and reload each time it is needed. Singleton has:
//   * a private constructor;
//   * a static factory method, usually named getInstance; must be synchronized, which means only one thread will be allowed in the method at a time, ensuring that only one object is created.
public class VisitorTicketTracker {
   private static VisitorTicketTracker instance;
   private VisitorTicketTracker() {} // private constructor to prevent creating instances with "new" and force using VisitorTicketTracker.getInstance() instead
   public static synchronized VisitorTicketTracker getInstance() { // synchronized!
      if (instance == null) {
         instance = new VisitorTicketTracker();
      }
      return instance;
   }
   // ...other members...
}
// If the instance is created in the field declaration (variant 1) or in a static initializer (variant 2), then the factory method doesn't need to be synchronized.

// Variant 1:
public class StaffRegister {
   private static final StaffRegister instance = new StaffRegister();
   private StaffRegister() {}
   public static StaffRegister getInstance() {
      return instance;
   }
   // ...other members...
}

// Variant 2:
public class StaffRegister {
   private static final StaffRegister instance;
   static {
      instance = new StaffRegister();
   }
   private StaffRegister() {}
   public static StaffRegister getInstance() {
      return instance;
   }
   // ...other members...
}