Wednesday, December 4

Iterator Design Pattern

Iterator design pattern in java

Lets write an class that has method next() and hasNext() which basically are backbone for iterator design pattern

This Iterator will be iterating over a collection represented by Collection class

Collection class consist of an array of elements that Iterator will be iterating over.

Additionally methods to add and remove elements from array are also available in Collection class

IteratorTestor class consist of all the scenarios where in




  1. First we are iterating over existing list of elements
  2. Then few elements are added to the array and It is again iterated over
  3. Then few elements are removed from the array and then It is again iterated over

Here is the Well compiled code to try this via java code

-=========================================================


public interface Iterator {
   
    public Object next();
    public boolean hasNext();

}


=========================================================


public interface Container {
   
    public Iterator getIterator();

}

=======================================================

This class consist of an inner class MyIterator which basically becomes the part of collection class and
thus it becomes easy for MyIterator class to work on variables of enclosing class. 


import java.lang.reflect.Array;

public class Collection implements Container {

    public
    String[] list = {"element1", "element2", "element3", "element4" };

    public int index;

    @Override
    public Iterator getIterator() {
        // TODO Auto-generated method stub
        return new MyIterator();
    }
   
    public void addElement(Object obj){
        int arrLength=list.length;
        arrLength++;
        String[] newArr =new String[arrLength];
        newArr[arrLength-1]=obj.toString();
        System.arraycopy(list, 0, newArr, 0, list.length);
        list=new String[newArr.length];
        System.arraycopy(newArr, 0, list, 0, newArr.length);


    }
   
    public void removeElement(Object obj){
        int arrLength=list.length;
        arrLength--;
        String[] newArr =new String[arrLength];
        System.arraycopy(list, 0, newArr, 0, list.length-1);
        list=new String[newArr.length];
        System.arraycopy(newArr, 0, list, 0, newArr.length);


    }


    private class MyIterator implements Iterator {

        @Override
        public Object next() {
            // TODO Auto-generated method stub
            if (hasNext()) {
                return list[index++];
            }
            return null;
        }

        @Override
        public boolean hasNext() {
            // TODO Auto-generated method stub
            if (list.length > index) {
                return true;
            }
            return false;
        }

    }

}

============================================================








public class IteratorTester {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Collection repo = new Collection();

        while (repo.getIterator().hasNext()) {
            System.out.println(repo.getIterator().next());
        }

        System.out.println("=================Lets Add Few More Elements========================");

        repo.index=0;
        repo.addElement("NewElemen1");
        repo.addElement("NewElemen2");
        repo.addElement("NewElemen3");
        while (repo.getIterator().hasNext()) {
            System.out.println(repo.getIterator().next());

        }
        System.out.println("===============Lets Remove few elements==========================");

        repo.index=0;
        repo.removeElement("Elemen1");
        repo.removeElement("Elemen2");
        while (repo.getIterator().hasNext()) {
            System.out.println(repo.getIterator().next());

        }


    }
}
===================================================






And this program will print below logs on console :


++++++++++++++++++++++++++++++++++++++++

element1
element2
element3
element4
=================Lets Add Few More Elements========================
element1
element2
element3
element4
NewElemen1
NewElemen2
NewElemen3
===============Lets Remove few elements==========================
element1
element2
element3
element4
NewElemen1

+++++++++++++++++++++++++++++++++++++++

Monday, December 2

Coding Practice to avoid error while using Object references






Let's understand this by example


import java.util.Date;

import java.util.Date;

public class Refree {

    public static void main(String args[]) {

        Date date = new Date();
        Dater coach = new Dater(date);
        System.out.println(coach.date);
        date.setYear(1111);
        System.out.println(coach.date);

    }

}

class Dater {
    public Date date;

    Dater(Date date) {
        this.date = date;
    }
}








This program will print

Mon Dec 02 16:33:48 IST 2013
Mon Dec 02 16:33:48 IST 3011


But in line date.setYear(1111); we only want to change the value of date and not coach instance But this code is changing values of date as well as coach.

So how can we avoid that :

Let's see another version of same program


import java.util.Date;

public class Refree {

    public static void main(String args[]) {

        Date date = new Date();
        Dater coach = new Dater(date);
        System.out.println(coach.date);
        date.setYear(1111);
        System.out.println(coach.date);

    }

}

class Dater {
    public Date date;

    Dater(Date date) {
        this.date = new Date(date.getTime());
    }
}




-->

This program will print

Mon Dec 02 16:36:36 IST 2013
Mon Dec 02 16:36:36 IST 2013



So that's what we wanted..

Command Design Pattern

Consider yourself a referee of a race where you need to give below commands to athletes

Ready -- Athlete to get ready for race
Set  ---
Athletes to all set to run
Go  ---
Athletes to run the race

How can we automate this in java using command design pattern .





Lets consider there is a Race class which defines there action


public class Race {

    public void getReady() {

        System.out.println("getting ready");
    }

    public void set() {
        System.out.println("setting running position");

    }

    public void go() {
        System.out.println("running");

    }
}



Now we need to create there command classes for these three actions

Let's create an interface first which basically will be uniformly implemented by all there command classes

Interface name is Position. It is declaring single method execute()


public interface Position {

    public void execute();
}







Next there command classes

Ready , Set and Go


public class Ready implements Position {

    Race race;   
    public Ready(Race race){
        this.race=race;
    }
    @Override
    public void execute() {

        race.getReady();

    }
}



public class Set implements Position {

    Race race;   
    public Set(Race race){
        this.race=race;
    }
   
    @Override
    public void execute() {
        race.set();
    }

}


public class Go implements Position {

    Race race;   
    public Go(Race race){
        this.race=race;
    }
   
    @Override
    public void execute() {
        race.go();

    }

}



-->


Every command class has one argument constructor which allows Command instances set Race class instance to execute the method on Race class.

Now it is duty of Referee to pass instance of Race class to Commands and Commands will execute() the method invoked inside execute() method.

Here is Referee class


public class Referee {

    public static void main(String args[]){
        Race race=new Race();
       
        Position position1=new Ready(race);
        Position position2=new Set(race);
        Position position3=new Go(race);
       
        position1.execute();
        position2.execute();
        position3.execute();

       
        }

}


Put together all these classes and execute program as java application. That will print below logs on console :



getting ready
setting running position
running



Sunday, December 1

Memento Design Pattern

This pattern talks about restoring the original state at any point of time . For example

I start with knowing the mileage of bike around reference value 80KM/h

I store this value in an string instance say : mileage

My reference value / Original value is 80KM/h

Now I start knowing mileage of various bikes and keep updating the the latest known mileage in same string instace :  mileage

current value might change from 80 to 70 to 50 to 40 to 100 and so on  depending upon the mileage of bikes.

So at any point of time If i want to know the reference value , It's no more there is mileage string.

So how do I make sure that I keep on working on current value as well as be able to retrieve the original value at any point of time.

There might be many ways you ca think across , Memento design pattern suggest a standard way to do that.

Pattern revolves around two contributors

Originator
Care Taker

Originator stores the original value in a non-modified way.
Care Taker takes care of returing current or original value at any point of time
Client directly interacts with Care taker to get current or original value


Now lets see how simple is it to implement it in java :


Originator class stores the original value and it can't be modified .







public class Originator {

    private final String mileage ="80";
   
    public String getFinalInstance(){
        return mileage;
    }

}
CareTaker provides method to get to current or original mileage at any point of time


public class CareTaker {

    private String mileage;
    public CareTaker(String instance) {
       this.mileage=instance;
    }

   public String saveCurrentInstance(String instance){
       this.mileage=instance;
       return this.mileage;
   }
  
   public String restoreDefaultInstance(){
       Originator finalInstance=new Originator();
      return  finalInstance.getFinalInstance();
}
   public String getCurrentValue(){
       return  mileage;
   }
}



-->


And here is our Client who interacts with CareTaker to play with current value and reach original value at any point of time.


public class MementoClient {

    public MementoClient() {
        // TODO Auto-generated constructor stub
    }
   
    public static void main(String args[]){
       
       System.out.println("Some original reference value is already set .......");
        CareTaker instance =new CareTaker("50");
        System.out.println("Let us create an instance with current value ::: 50");
        System.out.println("Lets find out the  original reference  value ");
       System.out.println("it is :::" + instance.restoreDefaultInstance());
        System.out.println("and the current value is :: ");
       System.out.println(instance.getCurrentValue());
        System.out.println("Lets change the value to 40");
        instance.saveCurrentInstance("40");
        System.out.println("Now current value is :::  " + instance.getCurrentValue());
        System.out.println("Let's again change the value to :::100");
        instance.saveCurrentInstance("100");
        System.out.println("Now current value is : " + instance.getCurrentValue());
        System.out.println("Now I want to get to the original  value");
        System.out.println("it is ::: " + instance.restoreDefaultInstance());

    }

}







Executing this application as java application will print below logs on console :

===============================
Some original reference value is already set .......
Let us create an instance with current value ::: 50
Lets find out the  original reference  value
it is :::80
and the current value is ::
50
Lets change the value to 40
Now current value is :::  40
Let's again change the value to :::100
Now current value is : 100
Now I want to get to the original  value
it is ::: 80

================================