Wednesday, 18 February 2015

Interpreter design Implementation

 Interpreter Design Pattern

Hibernate                                                                                              Core Java



Question:- What is Interpreter Design Pattern?
This design pattern falls under Behavioral design pattern. This pattern provides a way to evaluate language expression. This design pattern involves in implementing an expression interface which tells to interpret a particular context.

As per GOF :-“Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.”

Question:- When to use Interpreter design pattern?
This design pattern is used for specialized computer languages which are often used to describe communication protocols.This design pattern is also used in symbol processing engine, SQL parsing etc.
  • Examples in JDK API
java.util.Pattern and subclasses of java.text.Format are few implementation examples of interpreter pattern used in JDK.
  • Live examples of Interpreter design pattern
  1. Google Translator is an example of interpreter pattern where the input can be in any language and we can get the output interpreted in another language.
  2. In java itself, this design pattern is implemented where java compiler interprets the java source code into byte code that is understandable by JVM.

Drawback

During implementation of Interpreter design pattern, it requires large piece of code for error checking and expression evaluation. So when the grammer is complicated then the required piece of code is complicated and hence it is very difficult to maintain and provide efficient code.

In the below example,we will see a sample of using interpreter design pattern.

InterpreterImplemeter.java

package com.gaurav.designpattern.interpreter;

/**
 * @author Gaurav
 * 
 */
public class InterpreterImplemeter {

public String getBinaryConversion(int number) {
return Integer.toBinaryString(number);
}

public String getHexadecimalConversion(int number) {
return Integer.toHexString(number);
}
}

ExpressionConversion.java

package com.gaurav.designpattern.interpreter;

/**
 * @author Gaurav
 * 
 */
public interface ExpressionConversion {
public String interpretData(InterpreterImplemeter interpreter);
}

IntegerToBinary.java


package com.gaurav.designpattern.interpreter;

/**
 * @author Gaurav
 *
 */
public class IntegerToBinary implements ExpressionConversion{
private int number;
public IntegerToBinary(int num){
this.number = num;
}
@Override
public String interpretData(InterpreterImplemeter interpreter) {
return interpreter.getBinaryConversion(this.number);
}
}


IntegerToHexadecimal.java


package com.gaurav.designpattern.interpreter;

/**
 * @author Gaurav
 *
 */
public class IntegerToHexadecimal implements ExpressionConversion{
private int number;
public IntegerToHexadecimal(int num){
this.number = num;
}
@Override
public String interpretData(InterpreterImplemeter interpreter) {
return interpreter.getHexadecimalConversion(this.number);
}
}


InterpreterDesignPatternDemo.java


package com.gaurav.designpattern.interpreter;

import java.util.Scanner;

/**
 * @author Gaurav
 * 
 */
public class InterpreterDesignPatternDemo {
public InterpreterImplemeter interPreter;

public InterpreterDesignPatternDemo(InterpreterImplemeter i) {
this.interPreter = i;
}

public String binaryConverter(int num) {
ExpressionConversion expressionConverter = new IntegerToHexadecimal(num);
return expressionConverter.interpretData(interPreter);
}

public String hexadecimalConverter(int num) {
ExpressionConversion expressionConverter = new IntegerToBinary(num);
return expressionConverter.interpretData(interPreter);
}
public static void main(String args[]) {
InterpreterDesignPatternDemo client = new InterpreterDesignPatternDemo(
new InterpreterImplemeter());

Scanner scanner = new Scanner(System.in);
System.out.println("Enter the conversion type either binary or hexa : ");
String conversionType = scanner.nextLine();
System.out.println("Enter the number for conversion : ");
int number = scanner.nextInt();
if("binary".equalsIgnoreCase(conversionType))
System.out.println(number + " in binary is : " + client.binaryConverter(number));
else if("hexa".equalsIgnoreCase(conversionType))
System.out.println(number + " in hexadecimal is : " + client.hexadecimalConverter(number));
else{
System.out.println("Unable to convert, please provide correct conversion type as mentioned.");
}
}
}


Result : - 

1st Execution : 

Enter the conversion type either binary or hexa : 
binary
Enter the number for conversion : 
10
10 in binary is : a

2nd Execution : 

Enter the conversion type either binary or hexa : 
hexa
Enter the number for conversion : 
10
10 in hexadecimal is : 1010

3rd Execution : 

Enter the conversion type either binary or hexa : 
octa
Enter the number for conversion : 
10
Unable to convert, please provide correct conversion type as mentioned.

Tuesday, 17 February 2015

Command design pattern Implementation

Command Design Pattern

Hibernate                                                                                              Core Java


Question : - What is Command Design Pattern?
This pattern falls under behavioural pattern. All the information required to invoke a method is encapsulated in this pattern. One of the most popular framework “Struts” uses this design pattern. This pattern helps us to build our command objects into a “ready to run” state and also help to pass those objects to an "invoker" class which makes a callback to the execute() method of each class at the exact/appropriate time. This invoker object does not know about the logic which a command object contains, it only knows that it has to call an execute() method when an event occurs.

As per GOF :-“Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.”

Question : - When to use Command design pattern?
     1.  Performing action to process the complete workflow of request and response.
  1. Thread Pools – A thread pool class is having a method which adds a work item to an internal queue of tasks and these tasks will wait to be completed. It maintains a pool of threads that execute commands from the queue. The items available in the queue are known as command objects.
  2. For implementing Graphical User Interface menu items and buttons.
  3. In networking for playing online games – It might be require to send complete command objects across the network to be executed on multiple nodes.
  4. This pattern is also useful for wizards, progress bars, parallel processing e.t.c.
 Advantage of using command design pattern : -
  • This pattern helps to decouple the invoker and receiver implementation. Receiver knows how to process the request. 
  • Client creats a concrete command object and specifies to its receiver. 
  • An invoker object stores the concrete command object. Then the invoker issues a request by calling execute() method on the command object. 
  • The concrete command  object invoke operations on its receiver to carry out the request. 
  • Command implementation selects the method to invoke on receiver object, and it works as a bridge between receiver and action methods.
  • This(Command) pattern is easily extensible, we can add multiple action methods in receivers and create new Command implementations without changing the client code.
  • The disadvantage or drawback with this pattern is that the code gets huge and it is confusing with high number of action methods and their associations.
  • Fundamental terms of Command design pattern is Client, Invoker and Receiver.


In Jdk
Runnable interface (java.lang.Runnable) and Swing Action (javax.swing.Action) uses command design pattern.

In Live example 
we can think about the order placed online in any shopping site, where it executes for appropriate actions for calling chosen payment gateway for money deduction and confirming the client order with selected items. 

In the below example we will see how to implement this design pattern in Java programming.

Command .java

package com.gaurav.designpattern.command;

/**
 * @author gaurav
 * 
 */
public interface Command {

public void execute();

}

RemoteControl.java


package com.gaurav.designpattern.command;

/**
 * @author gaurav
 * 
 */
public class RemoteControl {

private Command putOn;
private Command putOff;

public RemoteControl(Command on, Command off) {
putOn = on;
putOff = off;
}

public void startOn() {
putOn.execute();
}

public void startOff() {
putOff.execute();
}
}


AirCondition.java

package com.gaurav.designpattern.command;

/**
 * @author gaurav
 * 
 */
public class AirCondition {
public void startCooling() {
System.out.println("Air condition is started cooling.");
}

public void stopCooling() {
System.out.println("Air condition is off now.");
}
}

LedTelevision.java

package com.gaurav.designpattern.command;

/**
 * @author gaurav
 * 
 */
public class LedTelevision {
public void turnOn() {
System.out.println("TV is on now.");
}

public void turnOff() {
System.out.println("TV is off.");
}
}


StartCoolingCommand.java


package com.gaurav.designpattern.command;

/**
 * @author gaurav
 * 
 */
public class StartCoolingCommand implements Command {
private AirCondition airCondition;

public StartCoolingCommand(AirCondition ac) {
airCondition = ac;
}

@Override
public void execute() {
airCondition.startCooling();
}

}


StopCoolingCommand.java


package com.gaurav.designpattern.command;

/**
 * @author gaurav
 * 
 */
public class StopCoolingCommand implements Command {
private AirCondition airCondition;

public StopCoolingCommand(AirCondition ac) {
airCondition = ac;
}

@Override
public void execute() {
airCondition.stopCooling();
}
}


TurnOnCommand.java


package com.gaurav.designpattern.command;

/**
 * @author gaurav
 * 
 */
public class TurnOnCommand implements Command {
private LedTelevision ledTelevision;

public TurnOnCommand(LedTelevision led) {
ledTelevision = led;
}

@Override
public void execute() {
ledTelevision.turnOn();
}

}


TurnOffCommand.java


package com.gaurav.designpattern.command;

/**
 * @author gaurav
 * 
 */
public class TurnOffCommand implements Command {
private LedTelevision ledTelevision;

public TurnOffCommand(LedTelevision led) {
ledTelevision = led;
}

@Override
public void execute() {
ledTelevision.turnOff();
}
}


CommandDesignPatternDemo.java


package com.gaurav.designpattern.command;

/**
 * @author gaurav
 * 
 */
public class CommandDesignPatternDemo {
public static void main(String args[]) {
AirCondition airCondition = new AirCondition();

StartCoolingCommand startCC = new StartCoolingCommand(airCondition);
StopCoolingCommand stopCC = new StopCoolingCommand(airCondition);

RemoteControl acRemoteControl = new RemoteControl(startCC, stopCC);
acRemoteControl.startOn();
acRemoteControl.startOff();

LedTelevision ledTV = new LedTelevision();
TurnOnCommand turnOnCommand = new TurnOnCommand(ledTV);
TurnOffCommand turnOffCommand = new TurnOffCommand(ledTV);

RemoteControl tvRemoteControl = new RemoteControl(turnOnCommand,
turnOffCommand);
tvRemoteControl.startOn();
tvRemoteControl.startOff();
}
}


Result:-

Air condition is started cooling
Air condition is off now
TV is on now.
TV is off.

Execution Flow:-

Friday, 6 February 2015

Chain of Responsibility Implementation

Chain of Responsibility Design Pattern

Hibernate                                                                                              Core Java


Question :- What is Chain of Responsibility Design Pattern?
Answer : - 


As per GOF : -"Gives more than one object an opportunity to handle a request by linking receiving objects together."

Question: - When to use Chain of Responsibility design pattern?

1. This design pattern helps to reduced coupling between the sender of a request and the receiver – the sender and receiver are not aware about each other means sender will not know which object in the chain will serve its request. In a chain of objects, the responsibility of deciding who to serve the request is left to the objects participating in the chains.

2. When more than one object may handle a request and the actual handler object is not know in advance or when requests follow a model - that is, some requests can be handled where they are generated while others must be forwarded to another object to be handled.

3. Dynamically, the chain of handlers can be modified.

Disadvantage : -
There is a possibility that a request could fall off the end of the chain without being handled.

Examples in JAVA API :

In JDK, we know about try-catch block, where we can mention multiple catch blocks. When exception occurs in try block then every catch block which are a kind of processor tries to process that exception, if catch clock is not able to handle that exception then it is forwarding to next catch block in chainalize manner. If last catch block is also not able to handle the occurred exception then the exception is thrown outside of the chain to the calling program.

javax.servlet.Filter -> doFilter()
The doFilter method of the Filter class is called by the container each time when a request or response is passed through the chain. The FilterChain object passed in to this method allows the Filter to pass on the request and response to the next entity in the chain for serving the request and providing the response to the intended recipient.

In Live example, we can think about the customer support of any organization which is based on chaining system or the hierarchy of a purchase department for approval of payment amount based on designation. 

Below we will implement the purchase department hierarchy example using chain of responsibility design pattern. In this example we will see that how request is processing in the chain and after process how we will get response after filtration.

AuthTypeRequest .java
package com.gaurav.designpattern.chainofresponsibility;

public class AuthTypeRequest {

private double amount;
private String expenditureType;

public AuthTypeRequest(String expenditure, double amount) {
this.expenditureType = expenditure;
this.amount = amount;
}

public double getAmount() {
return amount;
}

public void setAmount(double amt) {
amount = amt;
}

public String getExpenditureType() {
return expenditureType;
}

public void setExpenditureType(String expenditureType) {
this.expenditureType = expenditureType;
}

}

AuthorizationCapacity.java

package com.gaurav.designpattern.chainofresponsibility;

abstract class AuthorizationCapacity {

    protected final double limit = 50000;
    protected AuthorizationCapacity authCapacity;

    public void setOrganizationalHierarchy(AuthorizationCapacity authorizationCapacity){
        this.authCapacity = authorizationCapacity;
    }

    abstract public void serveRequest(AuthTypeRequest request);

}


HRManager.java

package com.gaurav.designpattern.chainofresponsibility;

public class HRManager extends AuthorizationCapacity {
    private final double EXPENDITURE_LIMIT = 10 * limit;

    public void serveRequest(AuthTypeRequest authTypeRequest ) {
        if( authTypeRequest.getAmount() < EXPENDITURE_LIMIT ){
            System.out.println("HR MANAGER EXPENDITURE LIMIT FOR APPROVAL IS : "+EXPENDITURE_LIMIT);
            System.out.println("AS SPENT AMOUNT "+authTypeRequest.getAmount()+" FALLS UNDER HIS EXPENDITURE LIMIT,SO HE CAN APPROVE THIS.");
        }
        else
           if( authCapacity != null)
          authCapacity.serveRequest(authTypeRequest);
  }
}

Director.java

package com.gaurav.designpattern.chainofresponsibility;

public class Director extends AuthorizationCapacity {
    private final double EXPENDITURE_LIMIT = 30 * limit;

    public void serveRequest(AuthTypeRequest authTypeRequest ) {
        if( authTypeRequest.getAmount() < EXPENDITURE_LIMIT ){
        System.out.println("DIRECTOR EXPENDITURE LIMIT FOR APPROVAL IS : "+EXPENDITURE_LIMIT);
       
        System.out.println("AS SPENT AMOUNT "+authTypeRequest.getAmount()+" FALLS UNDER HIS EXPENDITURE LIMIT,SO HE CAN APPROVE THIS.");
            }
        else
           if( authCapacity != null)
          authCapacity.serveRequest(authTypeRequest);
  }
}

VicePresident.java

package com.gaurav.designpattern.chainofresponsibility;

public class VicePresident extends AuthorizationCapacity {
    private final double EXPENDITURE_LIMIT = 50 * limit;

    public void serveRequest(AuthTypeRequest authTypeRequest ) {
        if( authTypeRequest.getAmount() < EXPENDITURE_LIMIT ){
       
        System.out.println("DIRECTOR EXPENDITURE LIMIT FOR APPROVAL IS : "+EXPENDITURE_LIMIT);
       
        System.out.println("AS SPENT AMOUNT "+authTypeRequest.getAmount()+" FALLS UNDER HIS EXPENDITURE LIMIT, SO HE CAN APPROVE THIS.");
        }
        else
           if( authCapacity != null)
          authCapacity.serveRequest(authTypeRequest);
  }
}

CEO.java

package com.gaurav.designpattern.chainofresponsibility;

public class CEO extends AuthorizationCapacity {
    private final double EXPENDITURE_LIMIT = 70 * limit;

    public void serveRequest(AuthTypeRequest authTypeRequest ) {
    if(authTypeRequest.getAmount()> EXPENDITURE_LIMIT)
    {
    System.out.println("AS PER POLICY THE EXPENDITURE LIMIT OF CEO IS : "+EXPENDITURE_LIMIT);
    System.out.println("AS SPENT AMOUNT "+authTypeRequest.getAmount()+" IS ABOUVE EXPENDITURE LIMIT OF CEO. SO HE NEEDS SHAREHOLDERS APPROVAL TO APPROVE THIS AMOUNT.");
    }
    if( authTypeRequest.getAmount() < EXPENDITURE_LIMIT ){
            System.out.println("A CEO IS THE OWNER OF THE COMPANY, \nSO HE IS HAVING POWER TO APPROVE COMPLETE AMOUNT \nBUT HE ALSO NEED TO TAKE OPINION FROM OTHER DIRECTORS SO THE APPROVAL AMOUNT IS i.e. INR : "+ EXPENDITURE_LIMIT);
            System.out.println("AS SPENT AMOUNT FALLS UNDER HIS EXPENDITURE LIMIT,SO HE CAN APPROVE THIS.");
        }
        else
           if( authCapacity != null)
          authCapacity.serveRequest(authTypeRequest);
  }
}

ChainofResponsibilityDesignPatternDemo.java

package com.gaurav.designpattern.chainofresponsibility;

import java.util.Scanner;

public class ChainofResponsibilityDesignPatternDemo {
private static Scanner enteredVal;

public static void main(String[] args) throws Exception{
HRManager hrmanager = new HRManager();
       Director director = new Director();
       VicePresident vp = new VicePresident();
       CEO ceo = new CEO();
      
       hrmanager.setOrganizationalHierarchy(director);
       director.setOrganizationalHierarchy(vp);
       vp.setOrganizationalHierarchy(ceo);
       
       enteredVal = new Scanner(System.in);
       
       System.out.println("Enter the expenditure type : ");
       String expenditureType = enteredVal.nextLine(); 
       
       System.out.println("Enter the amount spent for the work : ");
       double amount = enteredVal.nextDouble();
       
           System.out.println("Check inside the organization who is having limit to approve for expenditure : ");
           AuthTypeRequest authTypeRequest = new AuthTypeRequest(expenditureType, amount);
           hrmanager.serveRequest(authTypeRequest);

 }
}


Result:

Scenario 1 :

Enter the expenditure type : 
Stationary
Enter the amount spent for the work : 
50000
Check inside the organization who is having limit to approve for expenditure : 
HR MANAGER EXPENDITURE LIMIT FOR APPROVAL IS : 500000.0
AS SPENT AMOUNT 50000.0 FALLS UNDER HIS EXPENDITURE LIMIT,SO HE CAN APPROVE THIS.

Scenario 2 :

Enter the expenditure type : 
Resource Hiring
Enter the amount spent for the work : 
1000000
Check inside the organization who is having limit to approve for expenditure : 
DIRECTOR EXPENDITURE LIMIT FOR APPROVAL IS : 1500000.0
AS SPENT AMOUNT 1000000.0 FALLS UNDER HIS EXPENDITURE LIMIT,SO HE CAN APPROVE THIS.

Scenario 3 :

Enter the expenditure type : 
Campus renovation
Enter the amount spent for the work : 
2000000
Check inside the organization who is having limit to approve for expenditure : 
VICE PRESIDENT EXPENDITURE LIMIT FOR APPROVAL IS : 2500000.0
AS SPENT AMOUNT 2000000.0 FALLS UNDER HIS EXPENDITURE LIMIT, SO HE CAN APPROVE THIS.

Scenario 4 :

Enter the expenditure type : 
Company Extension
Enter the amount spent for the work : 
3000000
Check inside the organization who is having limit to approve for expenditure : 
A CEO IS THE OWNER OF THE COMPANY, 
SO HE IS HAVING POWER TO APPROVE COMPLETE AMOUNT 
BUT HE ALSO NEED TO TAKE OPINION FROM OTHER DIRECTORS SO THE APPROVAL AMOUNT IS i.e. INR : 3500000.0
AS SPENT AMOUNT FALLS UNDER HIS EXPENDITURE LIMIT,SO HE CAN APPROVE THIS.

Scenario 5 :

Enter the expenditure type : 
Share Listing
Enter the amount spent for the work : 
4000000
Check inside the organization who is having limit to approve for expenditure : 
AS PER POLICY THE EXPENDITURE LIMIT OF CEO IS : 3500000.0
AS SPENT AMOUNT 4000000.0 IS ABOUVE EXPENDITURE LIMIT OF CEO. SO HE NEEDS SHAREHOLDERS APPROVAL TO APPROVE THIS AMOUNT.