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 {

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

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

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

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


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

public class BadMood implements Mood {

   public String talk() {
     return "Not Nice";

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

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

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


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

public class NeutralMood implements Mood {

   public String talk() {
     return "Normal talking";

   public String think() {
     return "Normal Thinking";

   public String work() {
     return "Normal working";

   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();

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

   public void changeToNormalEnviroment(){
     //current environment is normal
     Mood neutralMood = new 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 environmnet = new Environment();
     //A human living in this environment,
     Human humanLivingInEnvironment = new Human();
     //Suddenly environment changes to a hostile environment
     //lets check how the human in this environment has been effected
     //Now , environment changes to a friendly one
     //Now , environment changes to a neutral one

   private static void checkHumanState(Environment environmnet){
     System.out.println("printing current state (Start)");
     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){;

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();

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

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


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.

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();
  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){,state);
//analogous to the time where you ask your friend the produce code back
 public Memento getMemento(Integer 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();

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


Tuesday, January 24, 2012

Going Technical....Command Pattern

I am back again with a different pattern today. The name of the pattern that we are going to look at today is Command pattern. Usually this pattern is very famous as well as sometimes it makes us confused as well, anyway let's try to look at an analogy of this pattern in real life.

Back then in the world , there were wars between nations for something valuable , sometimes they waged wars on acquiring a piece of land or for some other resource. Whatever the reason we know that a war is not pleasant , but for the sake of understanding the pattern let's assume that two parties were in a war and this happened during the times that they had only swords and horses as weapons and transportation.

During these times if some party had wanted to send a command to it's ally about what should have been the next action, the leader of the group would have written the command in a piece of paper ,possibly would have encrypted in a certain way and would have sent this through a trustworthy person.

Once this command had reached the ally the message would have been received by the leader of the ally and he would have ordered his warriors to act according to the command. In this case there was no need for the two leaders to know each other personally and they did not directly communicate to each other either. Also the first leader could have sent more than one message written in more than one papers. In such case the person who had been delivering the message to the other ally had had the privilege of passing the messages in a certain order , possibly following the instructions from the first leader.

Now it is a good time for us to look at command pattern in detail to have a better understanding on how the example and the pattern go together. Command pattern may be used in situations like explained above. If you need to decouple a sender and a receiver and encapsulate command related logic elsewhere , Command pattern is a good choice. Also this help in delayed or timed execution of a particular command as well as queuing the commands based on a certain set of rules.

In Command pattern , there are few actors involved ,

1. Sender
2. Receiver
3. Invoker
4. Command itself

If we take above analogy , the Sender would be the leader of the party , Receiver would be the leader of the ally, Invoker would be the warriors who were going to act , and the Command itself is the message written in the piece of paper. In this case we see that the Sender and the Receiver is decoupled and also the Sender could send more than one piece of paper containing completely different command as well. In such case Warriors would act on each command according to it's assigned priority. That means Command pattern would also help you queue more than one command and execute based on some sequence.

Lets try understanding some code now,

public class PartyLeader{

  private Command commandToAlly;
  //initiate a command to be sent to the Ally
  public void initiateCommand(){
    commandToAlly = new MoveToEast();

  public Command getCommandToAlly(){
    return this.commandToAlly;

public class AllyLeader{

  private Command commandFromParty;

  public void receiveCommandFromParty(Command commandFromParty){
    this.commandFromParty = commandFromParty;
  public void commandWarriors(){
    Warriors warriorsUnderAllyLeader = new Warriors();

public class Warriors{
  public void moveToEast(){
  public void moveToNorth(){
  public void moveToSouth(){
  public void moveToWest(){

public interface Command{
  void execute(Warriors warriors);

//Command sent using a paper to the ally
public class MoveToEast implements Command{
  public void execute(Warriors warriors){

//A main method to see all actors in action
public static void main(String args[]){

  //The leader of the party is initiating the command to Ally
  PartyLeader leaderOfTheParty = new PartyLeader();
  //This is as if the leader of the party writes the command in a piece of
  //paper and sending it via a messenger
  Command commandToAlly = leaderOfTheParty.getCommandToAlly();

  //now that the leader of the Ally
  AllyLeader leaderOfTheAlly = new AllyLeader();
  //Leader of the ally receives the command from the messenger and probably reads it
  //Then the leader of the Ally instructs his warriors what should be done

It is clear that the Sender (PartyLeader) does not have any idea about the Receiver (AllyLeader) , neither sender knows who is going to execute the command. And the Receiver does not know about the Sender , but knows what to do with the command. The actual work is done by the Invoker , (i.e Warriors in this case). By using a Command Sender and Receiver are decoupled well.

Note: Command pattern sometimes confuses us , if you have questions you may place a comment for which I could help answering...:)

Thursday, January 19, 2012

Going Technical....Mediator Pattern

Have you ever attempted to book a cab ? If yes then today's lesson is going to be easy for you. For the people who have not ever done that , I am going to give a crash course :). Well if you need to book a cab you just need to call the cab service provider's number and talk to the representative at the other end.

When you inform the representative about the pick up point and the destination he or she will do the coordination and pass this information to a cab which is nearer to your location. In this case you talked to the representative not to the cab driver. And the cab driver also talked to the representative , not to you directly. In short representative is becoming a medium for you to transfer the message that "you need a cab" , and the representative transfers a message to cab driver saying that "there is a passenger waiting for".

Imagine that if you ever had to book a cab by directly calling a cab driver, it would have been extremely difficult and chaotic. On the other hand you would have to know about all the numbers of cab drivers whom you could probably contact. But surely , we know that this is not going to work easy for us and we will be wasting time trying to get hold of a cab. Instead you get a representative who has all the information about the cab drivers such as contact numbers , current location etc.

Well that is the real life example , but how can we apply this in the field of software ? . Imagine for a moment that you have two or more applications which need to send messages among each other , possibly to do some application processing. Let's say the systems are SystemA , SystemB and SystemC. If these systems send messages to each other , it would be like,

1. From SystemA to SystemB
2. From SystemB to SystemA
3. From SystemB to SystemC
4. From SystemC to SystemB
5. From SystemC to SystemA
6. From SystemA to SystemC

If System A , System B , System C communicates as mentioned above , those will surely be making a spaghetti when communications are considered among them. It is chaotic , it is difficult to maintain and would waste lot of time and energy.

Now that , lets say we are going to introduce some other entity as a middleman among these systems and mandate those system to communicate to the middleman at the same time mandating the middleman to communicate to the systems whenever it is needed. Once this arrangement is in place , the middle man becomes a focal point. System A , System B and System C communicate to middleman as a client and middleman would communicate to any system which is acting as a receiver according to the request from a client.

In this case , systems do not communicate to each other directly , instead a mediator is used. The mediator would know to which system to send the messages received from the client. This set up will surely make it easy to maintain , would help specializing roles of the systems and would surely save some time and effort as well.

That is what we call as Mediator pattern , it is quite simple. Let's do some coding then....

 public abstract class System{
  private MiddleMan middleMan;
  public void registerMiddleman(MiddleMan middleMan){
   this.middleMan = middleMan
  public void sendExternalSystemMessage(String message , System system){
  public void receiveExternalMessage(String message , System receivedFrom){
   //do something with the message from another system

//defining systems

 public class SystemA extends System{
 public class SystemB extends System{
 public class SystemC extends System{

//defining Middleman

 public class MiddleMan{

  private ArrayList<System> systems = new ArrayList<System>();
  private Map<System,String> messageMap = new HashMap<System,String>();
  public void recordMessageFor(String message,System system){
  public void registerSystem(System system){
  public void sendMessages(){
   Set<System> keys = messageMap.keySet();
   Iterator<System> _it = keys.iterator();
    System system =;
    message = messageMap.get(system);

//A main method in another class

 public static void main(String[] args){

   System systemA = new SystemA();
   System systemB = new SystemB();
   System systemC = new SystemC();

   MiddleMan middleMan = new MiddleMan();

   //register middle man with each system,
   //this is as if all the cab drivers know the representative

   //register systems with middleman, this is as if representative knows
   //the all the cab drivers

   //send messages from systems to systems
   systemA.sendExternalSystemMessage("this is from A to B",systemB);
   systemB.sendExternalSystemMessage("this is from B to C",systemC);

   //middleman does the coordination...

Monday, January 9, 2012

Going Technical , Observer pattern ......

Here I am back again , to give you some insight into another GOF pattern , namely Observer pattern. Let's take a simple example to understand this pattern.

Nowadays phones are very common and many people are using those.We also know that two of most important functionalities of a phone is that making or receiving calls , and sending or receiving of short messages (SMS). Lets focus on receiving calls and receiving SMS(s). Also let's assume that a member of your family has gone to a competition and rest of the family is awaiting the result at home and it is about the time that he or she should either call you or send an SMS letting you know the result.

Now that in this case all the family members are paying great deal of attention to the phone and are expecting to have some form of communication from the other person. In case if the rings all the family members would try to quickly pick the phone up and receive the call , or else if a text is received all the members are eager to quickly pick up the phone and read the message. In other worlds all the family members are sort of observing the phone until a call or an sms is received. Now that I have mentioned the word "Observe" and you must have been hinted about the pattern a bit.

Let's look at the example in the context of the Observer pattern. In this case the family members are paying lot of attention to the phone observing it and waiting for a call or an SMS , in other words all the family members are observers now. If a call or sms is received they will be very quick and will respond to that by answering or reading the content. On the other hand we could call the phone as an object of which the family members are interested in. Also the state of the object would make them to react accordingly. Also the object would notify the observers, in this case by a ringing tone. In essence this is what you should try to achieve in Observer pattern. The pattern is used in situation where a group of things must be notified based on the events which happen in the other. In addition to that the group of things which must be notified would be registered with the subject so that subject can notify them when something important occurs in the subject itself.

In the above analogy the subject is the phone and the family members are the observers. And the attention that is paid by the family members are like observers getting registered themselves with the subject. Also the ringing of the phone can be seen as the notification by the subject to its registered observers.

Let's have a look at how we could do this with some code....

 public class Phone{
   private List<FamilyMember> observers = new ArrayList<FamilyMember>();

  public void ring(){

  public void notifyObservers(){
   Iterator<FamilyMember> iterator = observer.iterator();
    FamilyMember observer =;

  public void registerObserver(FamilyMember observer){

  public void unregisterObserver(FamilyMember observer){


 public abstract class FamilyMember{
  public abstract void notify();

 public class Brother extends FamilyMember{
  public void notify(){
   //notifying brother

 public class Sister extends FamilyMember{
  public void notify(){
   //notifying Sister

 public class Mother extends FamilyMember{
  public void notify(){
   //notifying Mother

//a main method to register observers with the subject
 public static void main(String args[]){
  //instantiate observers
  FamilyMember sister = new Sister();
  FamilyMember brother = new Brother();
  FamilyMember mother = new Mother();
  //instantiate subject
  Phone phone = new Phone();
  //register observers with subject
  //when some event occurs notify all the observers

This is basically what we call as an implementation of Observer pattern , the observers are registered with the subject and the subject would notify all the registered observers when an event occurs in the subject it self about which observers are interested in getting notified. Lets put this into our analogy, the family members are interested in receiving a call or a text to the phone and they are paying a great deal of attention to the phone , when the phone receives an SMS or a call it will notify all the family members by ringing itself.