How to implement Singleton Design Patterns in Java

How to Implement Singleton Design Patterns in Java

In this blog I am going to explain first What are design patterns and how to implement Singleton design patterns in Java. I am assuming the reader has a basic knowledge of java programming and object oriented concepts. Design Patterns have important role in software development. It is a best practice in software development to apply design patterns to perform specific tasks. As the name suggest design patterns are the design approaches to implement the tasks. These approaches reduce general problems that software developers face and easy to provide solutions for the problems.

There is a number of design patterns in Java. It depends on the nature of task what design pattern is suitable. Developer should understand the requirement, prepare design and apply the best suitable design pattern to implement.

Following are the few popular design patterns in Java. In this blog I am going to explain Singleton design pattern from the below list.

  • Singleton Design Pattern
  • Factory Design Pattern
  • Abstract Factory Design Pattern

Singleton Design patterns in Java

The purpose of following Singleton design pattern is to make a single instance that can be accessible globally through out the application. Singleton instances are static, once created can be used globally by calling its static method. No need to create instance of singleton class every time. Singleton design pattern lies under the category of Creational design pattern. This design pattern is very easy to implement and very useful in multithreaded environment.

How to implement Singleton Design pattern in Java

To implement Singleton design pattern I am creating following two classes.

    • SingletonClassDemo.java
    • SingletonDesignPatternTest.java

 

To make the class SingletonClassDemo need to follow the below instructions:

  • Class should be having a static instance for the same class.
  • Class should be having a private constructor.
  • Class should be having public method that return the singleton instance for the global use.
 public class SingletonClassDemo {

   private static SingletonClassDemo singletonInstance = new SingletonClassDemo();

   private SingletonClassDemo() {}

   public static SingletonClassDemo getInstance() {
      return singletonInstance;
   }

   public void printMessage() {
      System.out.println("This is a demo of singleton design pattern ");
   }
 }

Lazy Initialization Method with Singleton Or Singleton Double Check Method

In the first method, instance will be created even though it is not used at runtime. Lazy Initialization method avoids this problem and create single instance when it calls very first time.
Synchronization avoid the concurrent access of this method in multi threaded environment.

      public class SingletonClassDemo {

	   private static SingletonClassDemo singletonInstance = null;

	   private SingletonClassDemo() {}

	   public static SingletonClassDemo getInstance() {
	      if (singletonInstance == null) {
	    	  synchronized (SingletonClassDemo.class) {
		      if (singletonInstance == null) {
			singletonInstance = new SingletonClassDemo(); 
		      }
		  }
	      }
	      return singletonInstance;
	   }

	   public void printMessage() {
	      System.out.println("This is a demo of singleton design pattern ");
	   }
	 }

To call a singleton instance. I am creating a class SingletonDesignPatternTest that has main method. In the main method  I am calling a public method of class SingletonClassDemo  to get the instance (Object). All methods of singleton class can be called by this instance.

public class SingletonDesignPatternTest {

  public static void main(String[] args) {
    SingletonClassDemo singletonClass = SingletonClassDemo.getInstance();
       singletonClass.printMessage();
    }
}

Singleton with Enum

Singleton with Enum is the best approach to implement singleton design pattern. This method solved all the problems like changing the access modifier using reflection and Serialization/Deserialization problem. In Earlier methods if we serialize the singleton class then at the time of deserialize it creates a new instance. Singleton with Enum approach resolves all these issues and assure a single instance in JVM.

    public enum SingletonDemoWithEnum {
	INSTANCE;
    
        public void printMessage() {
	   System.out.println("This is a demo of singleton design pattern with enum");
	}
    }

Following is an example how to call a singleton instance in main method

    public class SingletonWithEnumMain {
	public static void main(String[] args) {
	    SingletonDemoWithEnum instance = SingletonDemoWithEnum.INSTANCE;
	    instance.printMessage();
	}
    }

How to set min/max values in angularjs Datepicker

showpersonalphoto
ahannan

Angularjs Datepicker: How to set min/max date in angularjs-datepicker.

This is an example to show how can we set minimum and maximum date in a angularjs-datepicker component so that user can select dates within the range. Other dates which do not lie in the range are not selectable.

Example code:

1.  Write code to develop search admission form:

<div class="module directive">
 <form role="form">
  <div class="form-group">
    <label>Admission Date:</label> 
      <datepicker date-format="MM/dd/yyyy"  date-min-limit="{{admissionDateMinLimit}}" date-max-limit="{{admissionDateMaxLimit}}" selector="form-control"> 
        <div class="input-group" >
          <input  type="text"  ng-model="admissionDate" class="form-control" placeholder="Select Admission Date"/>
            <span class="input-group-addon" style="cursor: pointer">
              <i class="fa fa-lg fa-calendar"></i>
            </span>
        </div>
      </datepicker>      
    <div>
      <button type="submit" ng-click="student.findAdmissions();" class="btn btn-default">Search</button>
    </div>                    
  </form>
</div>

2.  Write a angularjs directive that will popup search addmission form.
3.  Write code to set min/max date

angular.module('myApp')
    .directive('student', function AdmissionSearchDrctv () {
        return {
            restrict: 'EA',
            replace: true,
            scope: true,
            templateUrl: "admission.search.html",
            controllerAs: 'student',
            controller: function ( $scope) {
   
   var currentDate = new Date();
         $scope.admissionDateMaxLimit = currentDate.getMonth() + 1  + '/' + currentDate.getDate() + '/' + currentDate.getFullYear();
         $scope.admissionDateMinLimit = currentDate.getMonth() + '/' + currentDate.getDate() + '/' + currentDate.getFullYear();
   
            this.findAdmissions = function () { 
                    ----
                   ----
            }
        };
    });