Monday, March 3, 2014

Going Technical , Prototype pattern

Well this is the year of 2014 and I have not made a single post yet for this year. Frankly I did not have a good real life example for explaining the "Prototype" design pattern. Yes I know there is a very famous example of cells and the way those get divided could be used to explain this pattern. Hey tell you what , it has been overly used by many and I really wanted a completely new example.

Now , you must be thinking what analogy I have found for this. Let me tell you. Nowadays there is this news of "3D printing". I hope you guys have heard of this novel way of printing three dimensional object using a printer capable of doing it. Even NASA has used it in its' space program recently.This simple concept can be helpful in understanding the pattern "Prototype".

Assuming that I have a 3D printer there is a chance that I can print a three dimensional version of the very same printer effectively cloning it (this cloning is loosely referring the shape of the printer and the look. We may not be able to print a completely working version at one shot ). So the printer knows how to produce something exactly like the printer itself. As a client or the user all I have to do is to buy a 3D printer and press the "print" button on the printer after connecting to the power. Every time when I press the print button , it creates a three dimensional object exactly like itself. Not only that I do not have to spend the money and the time that may have been spent by the original manufacturer who manufactured the printer. In addition to that every time when my 3D printer prints an object which resembles itself I have the privilege of painting that with a color that I want. Well , all the description I made is exactly what we get in the case of Prototype pattern. Let me tell you all that in a more computer language specific way

So my 3D printer analogues to the prototype itself , the button which exposes the printing functionality analogues to the interface contract that I have to follow , the objects that I print with the 3D printer which are similar to the printer itself are the objects that could have been expensive to buy If I had attempted to buy them outside from a manufacturer and the ability to color the objects that I produced with my 3D printer can be seen as configuring cloned object in the way that a program requires.

I hope this explanation gives you a new way to think about the Prototype pattern. Let me write some code then,

public interface Cloneable{
   public Object clone();
}

public interface Printable{
    public Object print();
}

public class THREE_D_Printer implements Printable , Cloneable{

    public Object print(){
        THREE_D_Printer aCloneOfPrinter = (THREE_D_Printer)this.clone();
        //once the object is cloned it is natural to have that cloned object configured
        //in the way that is required
        Object config = new Object();
        aCloneOfPrinter.configure(config);
        return aCloneOfPrinter;
    }
    public Object clone(){
        //you either copy this object and change its' specific configuration
        //to suite to the one you need. Usually when initializing this object
        //it may be very expensive in terms of resources. So instead of simply
        //creating new objects by calling "new" operator on this the object
        //may be copied to another and configure the way it is needed
    }

   private void configure(Object cfg){
       //do configuration specific to your need
    }

}



//This is going to be the buyer class , it represents me buying the printer from a store
public class Buyer{
    public THREE_D_Printer buyPrinter(){
        return new THREE_D_Printer();
    }
}
   //main method
   ....
   public static void main(String[] args){
        Buyer buyer = new Buyer();
        THREE_D_Printer iiiDPrinter = buyer.buy();
        //use this iiiDPrinter as the prototype for creating other
        //printer objects with different colors or configurations
        THREE_D_Printer clonedPrinter = iiiDPrinter.print();
        //use iiiDPrinter instance to make any number of cloned objects
   }
   ....

Monday, May 13, 2013

Going technical...Builder pattern

"House" when I say this word I know many of you would imagine the place where you are currently living or the place where you lived when you were a kid. It is likely that two different individuals may have two different versions of the house that they are familiar with. But still the basic steps followed for the construction of those houses remain the same. Well now you must be thinking what those basic steps that I am talking about.

When a house is built regardless of the outside appearance of the house one must follow a fundamental sequence of actions to complete the house.

  • 1. Dig the land for foundation
  • 2. Lay the foundation
  • 3. Construct columns and beams
  • 4. Construct side walls or partition walls
  • 5. Fix the roof

In general any house that you can think of must have gone through the above stages of construction. Now that we are clear of the fact that we can generalize the process of constructing a house. We could identify this as a set of stages that must be followed to construct any house.

I guess now you are becoming clearer and clearer of what the title says. "Builder Pattern". So our builder will follow the above sequence and will successfully be able to build a house. If we introduce set of builders which follow the same steps of construction but add some additional touch to the final outcome we could have houses with different appearance.

How are we going to use this in software design. Yes , enough talking start coding then....
public class House {

 private String foundation;
 private String columns;
 private String beams;
 private String walls;
 private String roof;

 public String getFoundation() {
   return foundation;
 }
 public void setFoundation(String foundation) {
   this.foundation = foundation;
 }
 public String getColumns() {
   return columns;
 }
 public void setColumns(String columns) {
   this.columns = columns;
 }
 public String getBeams() {
   return beams;
 }
 public void setBeams(String beams) {
   this.beams = beams;
 }
 public String getWalls() {
   return walls;
 }
 public void setWalls(String walls) {
   this.walls = walls;
 }
 public String getRoof() {
   return roof;
 }
 public void setRoof(String roof) {
   this.roof = roof;
 }
}


public interface HouseBuilder {
 void digFoundation();
 void layFoundation();
 void constructColumnsBeams();
 void constructSideWallsPartitions();
 void fixRoof();
 House completeHouse();
}


public class CityHouseBuilder implements HouseBuilder {

 private House cityHouse = new House();

 public void digFoundation() {
   System.out.println("Dig foundation using an excavation machine");
 }

 public void layFoundation() {
   System.out.println("Lay foundation using Rubble , Cement and steel");
   cityHouse.setFoundation("Rubble , Cement , Steel");
 }

 public void constructColumnsBeams() {
   System.out.println("Construct columns and beams using steel and concrete");
   cityHouse.setColumns("Concrete , Steel");
   cityHouse.setBeams("Concrete . Steel");
 }

 public void constructSideWallsPartitions() {
   System.out.println("Construct side walls with bricks and cement");
   cityHouse.setWalls("Bricks , Cement");
 }

 public void fixRoof() {
   System.out.println("Fix roof with timber and roof tiles");
   cityHouse.setRoof("Timber , Roof Tiles");
 }

 public House completeHouse() {
   return this.cityHouse;
 }

}


public class VillageHouseBuilder implements HouseBuilder {

 private House villageHouse = new House();

 public void digFoundation() {
   System.out.println("Dig foundation using hand held tools");
 }

 public void layFoundation() {
   System.out.println("Lay a simple foundation using rubble and clay");
   villageHouse.setFoundation("Rubble and Clay");
 }

 public void constructColumnsBeams() {
   System.out.println("Fix wooded columns and wooden beams");
   villageHouse.setColumns("Wooden");
   villageHouse.setBeams("Wooden");
 }

 public void constructSideWallsPartitions() {
   System.out.println("Cover the side walls with hay and card board");
   villageHouse.setWalls("Hay and Cardboard");
 }

 public void fixRoof() {
   System.out.println("Fix the roof with hay");
   villageHouse.setRoof("Hay");
 }

 public House completeHouse() {
   return this.villageHouse;
 }

}


public class Main {

 public static void main(String[] args) {
   System.out.println("Village House :");
   //Build a Village House
   HouseBuilder builder = new VillageHouseBuilder();
   House house = buildHouse(builder);
   //
   System.out.println("City House :");
   //Build a City House
   builder = new CityHouseBuilder();
   house = buildHouse(builder);
 }

 public static House buildHouse(HouseBuilder builder){
   House house = null;
   builder.digFoundation();
   builder.layFoundation();
   builder.constructColumnsBeams();
   builder.constructSideWallsPartitions();
   builder.fixRoof();
   house = builder.completeHouse();
   return house;
 }

}

Sunday, March 10, 2013

Going Technical...Iterator design pattern

It has been quite sometime since I wrote the last post on this blog. In fact I tried few times to write something new but due to lack of time I was not able to do that. Also I was unable to find a simple yet elegant real life analogy to explain the "Iterator" design pattern.

Anyways now that I have found an analogy which may be good enough for this. Let's see whether you can grasp the idea without much effort.

We all are familiar with multistory buildings. Usually these buildings have some sort of fire alarming systems. When an accidental fire occurs these systems alert the occupants of the building so that they could move to a safe place. In addition to that when such fire alarming happens there may be an evacuation procedure to follow.Once the building occupants have moved to a safe ground someone would be in charge of making sure that all the occupants have arrived to the safe ground.Now that let's see how we could use this analogy to understand "Iterator" pattern.

"Iterator" design pattern is used when there is a need to inspect every single element in a group of elements and to do something with those. Usually this group of elements belongs to another parent data structure and when there is a need to inspect the elements in the group one has to request it from the parent data structure. The parent data structure is not supposed to reveal its internal information yet it has to allow inspection of all the elements

Well above paragraph tells us what Iterator design pattern is supposed to do. It is time to see how this fits to our analogy. Our analogy has a multistory building , occupants , fire alarming system and an evacuation procedure. The multistory building can be seen as the parent data structure. Occupants can be seen as the group of elements. Fire alarming system and evacuation procedure can be seen as the way how elements are exposed to outside for some sort of processing. When the evacuation procedure is followed occupants are supposed to take the stair case and walk to the safe ground one after the other.

Let's try putting these in code now,

package dranilev.blogspot.sg;

import java.util.ArrayList;
import java.util.List;

public class MultistoryBuilding implements FireAlarmAware{

  private List buildingOccupants = new ArrayList();

  public OccupantIterator evacuateOccupants() {
   OccupantIterator occupantIterator = new OccupantIterator();
   List iteratorOccupants = new ArrayList();
   iteratorOccupants.addAll(buildingOccupants);
   occupantIterator.setOccupants(iteratorOccupants);
   return occupantIterator;
  }

  public void occupyBuilding(Occupant occupant){
   this.buildingOccupants.add(occupant);
  }
}


package dranilev.blogspot.sg;

public interface FireAlarmAware {
  public OccupantIterator evacuateOccupants();
}


package dranilev.blogspot.sg;

import java.util.List;

public class OccupantIterator {
  private List occupants;

  public List getOccupants() {
   return occupants;
  }

  public void setOccupants(List occupants) {
   this.occupants = occupants;
  }

  public Occupant getNextOccupant(){
   Occupant nextOccupant = null;
   if(this.occupants != null && this.occupants.size() > 0){
    nextOccupant = this.occupants.get(0);
    this.occupants.remove(nextOccupant);
   }
   return nextOccupant;
  }

  public boolean hasNextOccupant(){
   boolean hasNext = false;
   if(this.occupants != null && this.occupants.size() > 0){
    hasNext = true;
   }
   return hasNext;
  }
}


package dranilev.blogspot.sg;

public class Occupant {
  private String name;
  private String age;
  private String sex;

  public String getName() {
   return name;
  }
  public void setName(String name) {
   this.name = name;
  }
  public String getAge() {
   return age;
  }
  public void setAge(String age) {
   this.age = age;
  }
  public String getSex() {
   return sex;
  }
  public void setSex(String sex) {
   this.sex = sex;
  }
  public void move(){
   System.out.println("moving " + name +" to a safe ground");
  }
}


package dranilev.blogspot.sg;

public class Main {

  public static void main(String[] args) {

   //construct a multi story building
   MultistoryBuilding multistoryBuilding = new MultistoryBuilding();
   //occupy the building
   for(int i = 0 ; i < 200 ; i++){
    Occupant occupant = new Occupant();
    occupant.setAge(i+"");
    occupant.setName("Occupant-"+i);
    if(i%2 ==0){
     occupant.setSex("Male");
    }else{
     occupant.setSex("Female");
    }
    multistoryBuilding.occupyBuilding(occupant);
  }

   //something happened , fire alarm activated evacuate occupants now
   OccupantIterator occupantIterator = multistoryBuilding.evacuateOccupants();
   while(occupantIterator.hasNextOccupant()){
    Occupant occupant = occupantIterator.getNextOccupant();
    occupant.move();
   }
  }

}


Thursday, September 20, 2012

Going Technical ....State Design Pattern

Just completed a hectic schedule , here I am back to write something for you!!!. Well today lets look at another GOF design pattern known as State pattern

Let's start this again with a simple example. We all know that humans are very sensitive towards their environment. If the environment is good and nice , a human living in that environment would feel good. If the environment is really hostile to a human living in that environment , he or she would feel really bad about it.If the environment is neither good nor bad then a human living in that environment would feel no difference. He or she will probably be in a neutral state in his or her mind.

It seems that the mental or physical state of the human is affected by the environment where he or she lives.We could consider this as "The state of the human's mind and body is effected by the environment in which he or she lives". It is obvious that depending on the mood of the human his or her reactions would be different. We can transform this understanding to the programming world as below,

"The behavior of an Object is a function of it's state". In the above analogy object is "The Human" , state is "The Mood" of the human and the nature of the environment is the triggering point for the state transition from one to another

In the programming world you may sometimes need to change the behavior of a given object based on the state of the object. In this case each state can be represented as a different class. When the object receives some form of a trigger it will change it's internal state. As a result of that the behavior of the object will change.

Let's put everything in to codes now ....

We have a top level interface representing a general "Mood" of a human


package sg.blogspot.dranilev;

public interface Mood {
   public String talk();
   public String think();
   public String work();
   public String walk();
}

Some moods that human may be having,

This is the good mood,

package sg.blogspot.dranilev;

public class GoodMood implements Mood {

   @Override
   public String talk() {
     return "Nice and cool";
   }

   @Override
   public String think() {
     return "Calm and focused , relaxed";
   }

   @Override
   public String work() {
     return "enjoy and focused well";
   }

   @Override
   public String walk() {
     return "Not in a hurry";
   }

}

This is a really bad mood,
package sg.blogspot.dranilev;

public class BadMood implements Mood {

   @Override
   public String talk() {
     return "Not Nice";
   }

   @Override
   public String think() {
     return "Confused , Unable to focus";
   }

   @Override
   public String work() {
     return "Stressful , not able to meet targets";
   }

   @Override
   public String walk() {
     return "In a hurry";
   }

}

This is a neutral mood ,
package sg.blogspot.dranilev;

public class NeutralMood implements Mood {

   @Override
   public String talk() {
     return "Normal talking";
   }

   @Override
   public String think() {
     return "Normal Thinking";
   }

   @Override
   public String work() {
     return "Normal working";
   }

   @Override
   public String walk() {
     return "Normal walking";
   }

}

Human , who has a mood at all the times,


package sg.blogspot.dranilev;

public class Human {

   private Mood mood;

   public String respondToTalk(){
     return getMood().talk();
   }

   public String respondToWalk(){
     return getMood().walk();
   }

   public String respondToWork(){
     return getMood().work();
   }

   public String respondToThought(){
     return getMood().think();
   }
   public Mood getMood() {
     return mood;
   }

   public void setMood(Mood mood) {
     this.mood = mood;
   }
}

Lets see the environment where human is living. Also see how the human changes his or her mood depending on the changes happened to the environment


package sg.blogspot.dranilev;

public class Environment {

   private Human humanInEnvironment = null;

   public void changeToHostileEnvironment(){
   //current environment is hostile , humans in this environment will be effected
     Mood badMood = new BadMood();
     getHumanInEnvironment().setMood(badMood);
   }

   public void changeToFriendlyEnvironment(){
     //current environment is friendly.
     Mood goodMood = new GoodMood();
     getHumanInEnvironment().setMood(goodMood);
   }

   public void changeToNormalEnviroment(){
     //current environment is normal
     Mood neutralMood = new NeutralMood();
     getHumanInEnvironment().setMood(neutralMood);
   }

   public Human getHumanInEnvironment() {
     return humanInEnvironment;
   }

   public void setHumanInEnvironment(Human humanInEnvironment) {
     this.humanInEnvironment = humanInEnvironment;
   }

}

Now that , lets see how Human changes his or her mood depending on the changes that happen to the environment


package sg.blogspot.dranilev;

public class StateExampleMain {

   public static void main(String[] args) {
     //Environment
     Environment environmnet = new Environment();
     //A human living in this environment,
     Human humanLivingInEnvironment = new Human();
     environmnet.setHumanInEnvironment(humanLivingInEnvironment);
     //Suddenly environment changes to a hostile environment
     environmnet.changeToHostileEnvironment();
     //lets check how the human in this environment has been effected
     checkHumanState(environmnet);
     //Now , environment changes to a friendly one
     environmnet.changeToFriendlyEnvironment();
     checkHumanState(environmnet);
     //Now , environment changes to a neutral one
     environmnet.changeToNormalEnviroment();
     checkHumanState(environmnet);
   }

   private static void checkHumanState(Environment environmnet){
     System.out.println("printing current state (Start)");
    System.out.println(environmnet.getHumanInEnvironment().respondToTalk());
    System.out.println(environmnet.getHumanInEnvironment().respondToThought());
    System.out.println(environmnet.getHumanInEnvironment().respondToWalk());
    System.out.println(environmnet.getHumanInEnvironment().respondToWork());
     System.out.println("printing current state (End)");
}

}

Wednesday, May 23, 2012

Going Technical ... Strategy Pattern

After sometime , here I am back again on my blog. Right now I am travelling in a train from one end to another end in Singapore. While I am travelling , I just now saw someone who was pulling all the credit cards that he got and inspected one by one for some reason. As soon as I saw this , I got a marvelous idea to blog something. The pattern is Strategy and I see a potential example in this instance to explain you.

He got three credit cards it seems , Visa , MasterCard and one more , I guess that was an American Express card. Surely he must be using all these three at different occasion. Lets say this person is going to a shop and buys some stuff. Of course , he got to pay for all the stuff he buys, now that lets say he is going to use any of those cards randomly at the counter where he is going to pay. Now the cashier probably uses the card given to him and swipes that card against a card reader at the counter. Most of the time we see that the cashier has got one card reader device , but it is used for many types of cards.

This means , the person who pays have got few strategies to pay , use Visa , MasterCard or American Express. But the cashier would only use one card reader device irrespective of the type of the credit card being used. This scenario is a fairly good example of how we could use Strategy pattern.

I hope you got the idea , simply and clearly. Let's look at some code then....

public interface CreditCard{
  public abstract void pay();
}


public class VisaCard implements CreditCard{
  public void pay(){
    //paying the amount using VisaCard
  }
}


public class MasterCard implements CreditCard{
  public void pay(){
    //paying the amount using MasterCard
  }
}


public class AmericanExpressCard implements CreditCard{
  public void pay(){
    //paying the amount using American Express Card
  }
}


now that lets see how the card reader is,

pubic class CreditCardReader{
  public void readCard(CreditCard creditCard){
    creditCard.pay();
  }
}


Lets put all these into a main method...

public static void main(String args[]){
  CreditCardReader cardReader = new CreditCardReader();

  //first strategy pay by Visa
  CreditCard creditCard = new VisaCard();
  cardReader.readCard(creditCard);

  //second strategy pay by MasterCard
  creditCard = new MasterCard();
  cardReader.readCard(creditCard);

  //Third strategy pay by American Express
  creditCard = new AmericanExpressCard();
  cardReader.readCard(creditCard);

}


That's it. Depending on the situation you could use any card , but the card reader stays the same. This approach is ideal for a situation where you have different algorithms for doing the same work. So depending on the scenario you could use any algorithms.

Note: the JAVA code above is not tested , since I just wrote this while travelling

Wednesday, April 25, 2012

Usage of Chain Of Responsibility in a practical application

Recently I have come across a situation where I had to process a collection of incoming XML files and run some logic according to the content of each and every XML message. At my office we are using file based electronic data interchange. Yes, I know that file based electronic data interchange may be somewhat an old timers approach , but still there are situations that you got to use it. Without stepping into any arguments , I just wanted to show you how this could be achieved using Chain Of Responsibility pattern.

There are few different operations that were needed on the incoming set of messages. Validation , Filtering , Sorting , Mapping and Aggregation. While these are the currently needed operations , in future we may have more and more different types of processing.

  • Validation : The set of the XML messages must be validated for a given set of rules. The rules are coming from a data base and those would be configurable depending on the requirement. The rules are configured based on the type of the message. Ex : if the property "message type" of an incoming XML message is "Sales Order" , then "project name" must not be empty
  • Filtering : The set of the XML messages must be filtered for a given set of rules. The rules are coming from a data base and those would be configurable depending on the requirement. The rules are configured based on the type of the message. Ex: if the XML message file name starts with "TMP_" , then filter all those messages
  • Sorting : Sorting happens based on the message content of each XML message. Ex: sort all the order items in a given XML message based on the order sequence number
  • Mapping & Aggregation : There operations are also done at each message level
When looking at each operation above , we could take each of those operations into individual classes and chain those classes according to requirement. Sometime you may want to execute Filtering first and Validation second or other way around. Sometimes you may want to turn off one operation , let's say Mapping and just go with the other operations. Later on there may be a new requirement for a completely new operation type on all the messages etc.. By considering all these it is better to have these operations separated into independent classes and combining them configurable.

Below is a possible high level design for this,

Below are some of the class diagrams , and sequence diagrams which may realize the above high level design.
VALIDATION
AGGREGATION
MAPPING

Friday, April 13, 2012

Going Technical...Memento Pattern

Today let's talk about another pattern , namely "Memento" pattern. This pattern is quite simple compared to many other pattern. So let's try to think about an analogy for this pattern first and later we will try to understand the pattern with the help of the analogy.

Imagine that your brother is calling you from home and he wants you to buy a new hard drive for his computer since the old one is no longer working. During the telephone conversation , your brother mentions the product code of the old hard drive. Let's say this product code is as long as 16 characters and you need to remember them before your brother hangs up the phone. Well in this situation , assume that you have not got a pen or a pencil with you making the situation even more difficult for you. But luckily a friend of yours is around in your apartment at this moment and you ask him to remember those characters for you.

Once the conversation is over , you would ask your friend those characters and then would probably write it down somewhere for future usage. In this scenario your friend did not really know for what those characters were and you did not give him any information about the conversation either. All you asked your friend was to keep the characters in his memory and give it back to you later when needed.

In "Memento" pattern this is what you would do. Asking another object B(let's say this is your friend) to keep the current state of the object A (let's say this is you) and later on when the object A needs to revert back to it's previous state , it would request object B to provide the needed information which is analogous to your friend telling you back the product code.

In general this is useful in undo operations in a particular process. It is also important to note that the external object (analogous to Object B , or your friend) which keeps track of the state of another object (analogous to Object A , or you) would not be able to see the internal information of the object A. Hence object A's information is not exposed (in other words , encapsulation is not violated). Usually the token which contains the information about the Object A is named as "Memento" and object B would manages such "Memento"s internally.

Well, now it is our time to see this in code,

//This class is analogous to YOU
public class ClassA{
 private String currentProductCode = "";

//this is analogous to asking your friend to keep this code recorded
 public Memento getState(){
  Memento _memento = new Memento();
  _memento.setProducCode("ABC-PRO-6767-REWS...");
  return _memento;
 }

//this is analogous to getting the product code from your friend and use it for your purpose
 public void updateState(Memento memento){
  this.currentProductCode = memento.getProductCode();
 }
}


//This class is analogous to your FRIEND
import java.util.HashMap;
import java.util.Map;

public class ClassB{
 private Map store = new HashMap();

//analogous to your friend recording the product code for you
//may be in a paper
 public void addMemento(Integer sequence , Memento state){
  this.store.put(sequence,state);
 }
//analogous to the time where you ask your friend the produce code back
 public Memento getMemento(Integer sequence){
  return this.store.get(sequence);
 }
}

//This is the structure which carries the internal information of object A
//usually in the analogy , you could assume this one could be a note book

public class Memento{
 private String productCode;
 public String getProductCode(){
  return this.productCode;
 }
 public void setProducCode(String productCode){
  this.productCode = productCode;
 }
}


//everything in a main method
public static void main(String[] args){
 //you are telling the product code to your friend here
 ClassA a = new ClassA();
 Memento state = a.getState();

 //your friend is recording the product code
 ClassB b = new ClassB();
 b.addMemento(1,state);

 //later , you will get that back from your friend
 Memento memento = b.getMemento(1);
 a.updateState(memento);

}