Tech Kraft

Documentum, AWS, Java, Ruby on Rails, Linux, Windows, App Servers


Java: Singleton Pattern

In most cases, instances of objects are created, which result in several objects being created from the same class. Using the Singleton pattern, we can ensure that only a single object of this class is created during the lifetime of the application.

Step 1: Create a Singleton Class

public class SingletonClass
{
      //Create singleton object
      private static SingletonClass singletonInstance = new SingletonClass();
      //Create private constructor so this class cannot be instantiated
      private SingletonClass() {}
      //Get an instance of this class
      public static SingletonClass getInstance() 
     {
          return singletonInstance;
     }
      public void message() {          System.out.println("Singleton Instance");
     }
}

Singleton Demo:

public class SingletonDemo {
     public static void main (String[] args) {
          //The constructor SingleObject() is not available
          //SingletonClass mySingleton= new SingletonClass();

          //Correct Way
          SingletonClass mySingleton= SingletonClass.getInstance();

          //show the message
          mySingleton.showMessage(
     }
}


Leave a comment

About Me

Senior Software Engineer professional with over 16 years of success with multiple open source technologies and various Content Management platforms and solutions.

Proven technical abilities through numerous projects involving enterprise web application design and development, application installation, configuration and support, and workflow and collaboration system designs.

  • Ability to learn new technologies and platforms quickly and apply them to the task at hand.
  • Excellent analytical skills, and strong communication and collaboration abilities.
  • Technical emphasis in including but not limited to Java, Ruby on Rails, Documentum and Alfresco
    in both Linux and Windows based environments

Newsletter