Showing posts with label Design Pattern. Show all posts
Showing posts with label Design Pattern. Show all posts

Wednesday, 4 March 2015

Iterator Design Implementation

Iterator Design Pattern


Question:- What is Iterator Design Pattern?

This design pattern falls under Behavioral design pattern. This pattern is used to provide a command and standard way to tranverse through a collection of objects.

As per GOF :-“Provides a way to access the elements of an aggregate object without exposing its underlying represenation.”

An aggregate object is an object that contains other objects for the purpose of grouping those objects as an unit.
Participants of Iterator interface
  • Iterator – defines an interface for accessing and traversing elements.
  • Aggregate – Like a factory method, it defines an interface for creating an iterator object.
  • Concrete Aggregate – This implements the iterator interface and keeps track of the current position in the traversal.
Question:- When to use Iterator design pattern?
This pattern provides a mechanism that allows all elements of a collection to be accessed sequentially, with some operation being performed on each element. With the help of this mechanism we can iterate or looping over an encapsulated group of objects.
  • If we want to access a group of objects without exposing its internal representation.
  • If there are many traversals of objects need to be supported in the collection. It supports multiple, concurrent traversals.

Examples in JDK API
  • implementations of java.util.Iterator and its subclasses.
  • implementations of java.util.Enumeration

Live examples of Iterator design pattern

Iterating over a number of DTH channels or traversing through a song playlist using MP3 player are the live examples of this design pattern.

In the below example, we will see the implementation of Iterator design pattern

DTHChannelMenuEnum.java

package com.gaurav.designpattern.iterator;
/**
 * @author Gaurav
 * 
 */
public enum DTHChannelMenuEnum {
HINDI, ENGLISH, TELEGU, ALL
}

DTHChannels.java

package com.gaurav.designpattern.iterator;
/**
 * @author Gaurav
 * 
 */
public class DTHChannels {
private DTHChannelMenuEnum dthChannelMenuEnum;
private double channelFrequency;

public DTHChannels(DTHChannelMenuEnum channelEnum, double chFreq) {
this.dthChannelMenuEnum = channelEnum;
this.channelFrequency = chFreq;
}

public DTHChannelMenuEnum getDthChannelMenuEnum() {
return dthChannelMenuEnum;
}

public double getChannelFrequency() {
return channelFrequency;
}

@Override
public String toString() {
return "DTHChannelMenuEnum=" + this.dthChannelMenuEnum
+ " , ChannelFrequency=" + this.channelFrequency;
}
}


Channels.java


package com.gaurav.designpattern.iterator;
/**
 * @author Gaurav
 * 
 */
public interface Channels {
 
public void addChannelInFavouriteMenu(DTHChannels dthChannels);
     
   public void removeChannelFromFavouriteMenu(DTHChannels dthChannels);
    
   public DTHMenuChannelIterator iterator(DTHChannelMenuEnum dthChannelMenuEnum);
}



DTHMenuChannelIterator.java


package com.gaurav.designpattern.iterator;
/**
 * @author Gaurav
 * 
 */
public interface DTHMenuChannelIterator {
 
   public boolean hasNext();
     
   public DTHChannels next();
}



ChannelsImpl.java


package com.gaurav.designpattern.iterator;
/**
 * @author Gaurav
 * 
 */
import java.util.ArrayList;
import java.util.List;

public class ChannelsImpl implements Channels{
private List<DTHChannels> dthChannelList = new ArrayList<DTHChannels>();

@Override
public void addChannelInFavouriteMenu(DTHChannels dthChannels) {
this.dthChannelList.add(dthChannels);
System.out.println(dthChannels.getDthChannelMenuEnum()+" channel with frequency "+dthChannels.getChannelFrequency()+" is added in the Favourite Menu.");
}

@Override
public void removeChannelFromFavouriteMenu(DTHChannels dthChannels) {
this.dthChannelList.remove(dthChannels);
System.out.println(dthChannels.getDthChannelMenuEnum()+" channel with frequency "+dthChannels.getChannelFrequency()+" is removed from the Favourite Menu.");
}

@Override
public DTHMenuChannelIterator iterator(DTHChannelMenuEnum dthChannelMenuEnum) {
System.out.println("\nTraversing for all DTH channels : ");
return new DTHMenuChannelIteratorImpl(dthChannelMenuEnum, this.dthChannelList);
}
private class DTHMenuChannelIteratorImpl implements DTHMenuChannelIterator
{

private DTHChannelMenuEnum dthChannelMenuEnum;
        private List<DTHChannels> channels;
        private int currentPosition;
        public DTHMenuChannelIteratorImpl(DTHChannelMenuEnum channelEnum,
                List<DTHChannels> dthChannelsArrList) {
            this.dthChannelMenuEnum = channelEnum;
            this.channels = dthChannelsArrList;
        }
        @Override
        public boolean hasNext() {
            while (currentPosition < channels.size()) {
            DTHChannels c = channels.get(currentPosition);
                if (c.getDthChannelMenuEnum().equals(dthChannelMenuEnum) || dthChannelMenuEnum.equals(DTHChannelMenuEnum.ALL)) {
                    return true;
                } else
                    currentPosition++;
            }
            return false;
        }
        @Override
        public DTHChannels next() {
        DTHChannels c = channels.get(currentPosition);
            currentPosition++;
            return c;
        }
    }
}



IteratorDesignPatternDemo.java



package com.gaurav.designpattern.iterator;
/**
 * @author Gaurav
 * 
 */
public class IteratorDesignPatternDemo {
private static Channels retrieveChannels() {
Channels channels = new ChannelsImpl();
channels.addChannelInFavouriteMenu(new DTHChannels(
DTHChannelMenuEnum.HINDI, 98.7));
channels.addChannelInFavouriteMenu(new DTHChannels(
DTHChannelMenuEnum.ENGLISH, 99.8));
channels.addChannelInFavouriteMenu(new DTHChannels(
DTHChannelMenuEnum.TELEGU, 100.2));
channels.addChannelInFavouriteMenu(new DTHChannels(
DTHChannelMenuEnum.HINDI, 95.3));
channels.addChannelInFavouriteMenu(new DTHChannels(
DTHChannelMenuEnum.TELEGU, 98.9));
channels.addChannelInFavouriteMenu(new DTHChannels(
DTHChannelMenuEnum.ENGLISH, 95.3));
channels.addChannelInFavouriteMenu(new DTHChannels(
DTHChannelMenuEnum.HINDI, 105.6));
channels.addChannelInFavouriteMenu(new DTHChannels(
DTHChannelMenuEnum.HINDI, 111.4));
channels.addChannelInFavouriteMenu(new DTHChannels(
DTHChannelMenuEnum.HINDI, 112.9));
return channels;
}
public static void main(String[] args) {
Channels channels = retrieveChannels();
DTHMenuChannelIterator allChannelIterator = channels
.iterator(DTHChannelMenuEnum.ALL);
System.out.println("\nALL available Channels are : \n");
while (allChannelIterator.hasNext()) {
DTHChannels dthChannel = allChannelIterator.next();
System.out.println(dthChannel.toString());
}
System.out.println("\n---------------------------------------------------------------");
DTHMenuChannelIterator hindiChannelIterator = channels
.iterator(DTHChannelMenuEnum.HINDI);
System.out.println("\nHindi available Channels are : \n");
while (hindiChannelIterator.hasNext()) {
DTHChannels dthChannel = hindiChannelIterator.next();
System.out.println(dthChannel.toString());
}
}

}


Result : -

HINDI channel with frequency 98.7 is added in the Favourite Menu.
ENGLISH channel with frequency 99.8 is added in the Favourite Menu.
TELEGU channel with frequency 100.2 is added in the Favourite Menu.
HINDI channel with frequency 95.3 is added in the Favourite Menu.
TELEGU channel with frequency 98.9 is added in the Favourite Menu.
ENGLISH channel with frequency 95.3 is added in the Favourite Menu.
HINDI channel with frequency 105.6 is added in the Favourite Menu.
HINDI channel with frequency 111.4 is added in the Favourite Menu.
HINDI channel with frequency 112.9 is added in the Favourite Menu.

Traversing for all DTH channels : 

ALL available Channels are : 

DTHChannelMenuEnum=HINDI , ChannelFrequency=98.7
DTHChannelMenuEnum=ENGLISH , ChannelFrequency=99.8
DTHChannelMenuEnum=TELEGU , ChannelFrequency=100.2
DTHChannelMenuEnum=HINDI , ChannelFrequency=95.3
DTHChannelMenuEnum=TELEGU , ChannelFrequency=98.9
DTHChannelMenuEnum=ENGLISH , ChannelFrequency=95.3
DTHChannelMenuEnum=HINDI , ChannelFrequency=105.6
DTHChannelMenuEnum=HINDI , ChannelFrequency=111.4
DTHChannelMenuEnum=HINDI , ChannelFrequency=112.9

---------------------------------------------------------------

Traversing for all DTH channels : 

Hindi available Channels are : 

DTHChannelMenuEnum=HINDI , ChannelFrequency=98.7
DTHChannelMenuEnum=HINDI , ChannelFrequency=95.3
DTHChannelMenuEnum=HINDI , ChannelFrequency=105.6
DTHChannelMenuEnum=HINDI , ChannelFrequency=111.4
DTHChannelMenuEnum=HINDI , ChannelFrequency=112.9

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.Patternand subclasses of java.text.Formatare 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:-