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,

//Sender
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;
  }
}

//Receiver
public class AllyLeader{

  private Command commandFromParty;

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

//Invoker
public class Warriors{
  public void moveToEast(){
  }
  public void moveToNorth(){
  }
  public void moveToSouth(){
  }
  public void moveToWest(){
  }
}

//Command
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){
     warriors.moveToEast();
  }
}

//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();
  leaderOfTheParty.initiateCommand();
  //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
  leaderOfTheAlly.receiveCommandFromParty(commandToAlly);
  //Then the leader of the Ally instructs his warriors what should be done
  leaderOfTheAlly.commandWarriors();
}


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){
   middleMan.recordMessageFor(message,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){
   messageMap.put(system,message);
  }
  public void registerSystem(System system){
   systems.add(system);
  }
  public void sendMessages(){
   Set<System> keys = messageMap.keySet();
   Iterator<System> _it = keys.iterator();
   while(_it.hasNext()){
    System system = _it.next();
    message = messageMap.get(system);
    system.receiveExternalMessage(message,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
   systemA.registerMiddleman(middleMan);
   systemB.registerMiddleman(middleMan);
   systemC.registerMiddleman(middleMan);

   //register systems with middleman, this is as if representative knows
   //the all the cab drivers
   middleMan.registerSystem(systemA);
   middleMan.registerSystem(systemB);
   middleMan.registerSystem(systemC);

   //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...
   middleMan.sendMessages();
 }



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....

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

  public void ring(){
   notifyObservers();
  }

  public void notifyObservers(){
   Iterator<FamilyMember> iterator = observer.iterator();
   while(iterator.hasNext()){
    FamilyMember observer = iterator.next();
    observer.notify();
   }
  }

  public void registerObserver(FamilyMember observer){
   observers.add(observer);
  }

  public void unregisterObserver(FamilyMember observer){
   observers.remove(observer);
  }
 }

//Observers

 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
  phone.registerObserver(sister);
  phone.registerObserver(brother);
  phone.registerObserver(mother);
  //when some event occurs notify all the observers
  phone.ring();
 }




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.

Wednesday, December 7, 2011

Fear of the Unknown...

We all fear the Unknown , if it is put in a context it could be understood clearly. We all fear our future , at least we worry about it thinking that what could happen tomorrow , may be after one year , may be after five years. Is there a way to overcome this ? , frankly I do not know. May be we could do some planning , but after all the plans are meant to be changed as well. So what can we do? can we leave it to our fate and just carry on...May be it could work. But are we strong enough in faith to let it happen that way ?. It could be quite difficult I would say..Not knowing what happens in the next minute may not really matter that much , but not knowing what might happen after few years probably matter much.Predicting the future would be useful to a certain extent to feel a little bit of relieved. Anyways , there is absolutely nothing we could do about this , just Keep Calm and Carry On somehow...

Wednesday, November 30, 2011

Me...

Unfairly judged
An Individual
Wading through
Difficult times
Looking for
A resting ground
Where there is
Endless Peace...

Thursday, November 10, 2011

Going Technical .......Chain Of Responsibility

Well it seems I get to write a bit more in this month :) , without much ado lets jump into the subject straight away. The pattern that we are going to talk about today is Chain Of Responsibility and it is one of those behavioral patterns introduced in GOF patterns.

What can you imagine when you think the name of the pattern itself , mmmmm.... something like a chain that we used to keep a dog not to run away...well kind of. But the difference is that this chain is going to be made of virtual objects in the memory of a computer which you can't see...but lets try to imagine it!

I hope you have seen automated car washing facilities , well if you have seen them this is quite easy to understand. Usually at those places when you drive in and leave the car at the right place , the automated washing facility would first spray water on the car , and then the car is slowly moved to a section where a cleansing form is applied to it , and then the car is slowly moved to a section where it will be washed , and then the car is slowly moved to a section where a dryer would start drying wet surface of the car. And at last the car would be slowly moved out to another section where you could just get in and drive again.

Well in the above analogy , you see that each section has its individual responsibility. Once section spray water on the car , the other section put cleansing form , the other section washes cleansing form and the last section dries the surface of the car. When the car is moved out of the facility , the final shape of the car still remains the same , but it would look more cleaner than it was. In the chain of responsibility pattern you would do the same. Means you would have different classes which executes a certain logic (analogues to washing , forming , drying etc) over a given object (analogues to car). And there would be a way to chain these classes one after the other as well.

OK lets see some code now....

public abstract class CarWashChain{
 private CarWashChain nextChain;

 public void setNextInChain(CarWashChain chain){
  this.nextChain = chain;
 }

 public CarWashChain getNextInChain(){
  return this.nextChain;
 }

 public abstract void doWork(Car car);

}

public class SprayWater extends CarWashChain{
 public void doWork(Car car){
  //spray the car with water first...

  //send to the next in the chain if any
  if(getNextInChain() != null){
   getNextInChain().doWork(car);
  }
 }
}

public class SprayForm extends CarWashChain{
 public void doWork(Car car){
  //spray cleansing form to the car for cleaning

  if(getNextInChain() != null){
   getNextInChain().doWork(car);
  }
 }
}

public class ClearForm extends CarWashChain{
 public void doWork(Car car){
  //put water and wash the car after applying cleansing form

  if(getNextInChain() != null){
   getNextInChain().doWork(car);
  }
 }
}

public class Dry extends CarWashChain{
 public void doWork(Car car){
  //dry the surface of the car now

  if(getNextInChain() != null){
   getNextInChain().doWork(car);
  }

 }
}

Now we have defined the chain elements , what is left is putting them in the chain

//Only main methods is shown here
public static void main(String[] args){

 SprayWater sprayWaterChainElement = new SprayWater();
 SprayForm sprayFormChainElement = new SprayForm();
 ClearForm clearFormChainElement = new ClearForm();
 Dry dryChainElement = new Dry();

 //Now that chain all these in one
 sprayWaterChainElement.setNextInChain(sprayFormChainElement);
 sprayFormChainElement.setNextInChain(sprayFormChainElement);
 sprayFormChainElement.setNextInChain(clearFormChainElement);
 clearFormChainElement.setNextInChain(dryChainElement);

 //invoke the chain , now this will execute all the chain elements with their respective logic
 Car car = new Car();
 sprayWaterChainElement.doWork(car);
}


well that is all for today , hope you have got some idea of this pattern too!!!. Do add a comment if you like this

Thursday, November 3, 2011

Going Technical .....Template Pattern

Again back to my blog , I have been busy with some other assignments for the past few months.Hence never got a chance to step back to this yard recently.However today I managed to grab some of my time to write something technical for all of the visitors of this blog (Not sure how many since I do not seem to get many comments :))

Ok what are we going to learn today , well the title says all of it!!, we gonna see what "Template Pattern" is. Template pattern is one of those Gang OF Four patterns and it falls under the category of behavioral patterns. well what ever lets see what it really means....

I hope all of you are familiar with cup cakes. well what is that got to do with this? one might ask.. Let me tell you , to make cup cake what we do first is buying or making a small cup like moulds made out of possibly some sort of a hard material. And then we would prepare necessary cake mixture and pour this mixture into those moulds. After that we would keep these moulds filled with cake mixture into an oven for backing. Not only that you could put some chocolate on top of one cup cake and some icing on top of another cup cake. Like that you could make different cup cakes with different appearance in color , different taste as well. Now that lets see how this is analogues to Template design pattern.

In simple terms I used moulds which are of the same geometrical shape for making cup cakes of different taste and color. But the fundamental shape of the cup cake was not changed. And I could also use the same set of moulds to make more cup cakes of different taste and color as well. So template pattern is also the same , you make a template class which is similar to the moulds and then define the stuff that need not be changed or must not be changed. It is as if the fundamental physical appearance of the cup cake moulds remain the same.Then what did we do ? we put cake mixture , this is as if you extend the original template class and write your own logic , but do not change the stuff that was defined in the template class. It is as if when you bake cup cakes you are sure that the shape of the cup cake will be determined by the shape of the moulds used.

Let's see some code in action,

public abstract class CupCakeMould{

  public void makeCupCake(){
   fillWithTheCakeMixture();
   addColor();
   addChocolate();
   addIcing();
  }

  //These abstract methods are expected to be implemented by the
  //sub class and define required logic
  public abstract void fillWithTheCakeMixture();
  public abstract void addColor();
  public abstract void addChocolate();
  public abstract void addIcing();

}

//extending classes

public class CupCakeWithIcing extends CupCakeMould{
  public abstract void fillWithTheCakeMixture(){
   //logic to fill the mould with cake mixture
  }
  public abstract void addColor(){
   //add logic if you need to add color to this cake
  }
  public abstract void addChocolate(){
   //add logic if you need to add chocolate to this cake
  }
  public abstract void addIcing(){
   //add logic if you need to add icing to this cake
  }
}



public class CupCakeWithChocolate extends CupCakeMould{
  public abstract void fillWithTheCakeMixture(){
   //logic to fill the mould with cake mixture
  }
  public abstract void addColor(){
   //add logic if you need to add color to this cake
  }
  public abstract void addChocolate(){
   //add logic if you need to add chocolate to this cake
  }
  public abstract void addIcing(){
   //add logic if you need to add icing to this cake
  }
}


//usage of this
//only main method is shown for clarity
  public static void main(String args[]){
   CupCakeMould cupCake = new CupCakeWithIcing();
   //This will make a cup cake which will have icing on it. See that you did not
   //change the original algorithm on how the cake is made , only what    the cake is made
   //from. You let the sub classes to decide it
   cupCake.makeCupCake();
   //if you want some other cake
   CupCakeMould cupCake2 = new CupCakeWithChocolate();
   cupCake2.makeCupCake();

}

Tuesday, July 26, 2011

Virtual Warehouse Management System (VWMS)

VWMS does not exist in reality yet , it is an idea which may have a paradigm shift in how we develop and design Warehouse Management Systems (WMS). Usually WMS systems are browser based (IE , Chrome , Firefox ) applications. These applications are having just a user interface to collect whatever the input from the user and execute business logic based on the given inputs. For the user he or she would not see the real time representation of the Warehouse that is being managed using the system. In fact for user to have a glimpse of how much room is occupied in warehouse he or she would have to get a report from the system or physically visit the warehouse and see. This is the typical way of developing any web based application today.

But what if user gets to see a model of existing warehouse as it is in a virtual world where user could do movements just by using mouse gestures such as drag , drop , click , select , double click etc. ?. This is where the concept of VWMS comes in to the picture. VWMS is a three dimensional model of the real warehouse and user will see the warehouse as it is at any given time. All the movements of different types of goods can be done by the user just by doing drag , drop , select actions. When the actions are performed on a virtual object in the virtual model those will be recorded in a database for later usage. This is exactly similar to what we see today's virtual games.

VWMS will definitely improve the efficiency of operations as well as improve the ability to receive exact state of the warehouse. In addition to that when reports are needed user could just get it done with the data that is recorded when movements are performed in the virtual model. Below are list of the scenarios that may come across,

1. User selects a shelf and the system will provide information about the shelf , such as the type of the goods stored , size of the shelf , approximate weight , available volume etc

2. Use could drag good from one shelf and drop to another shelf

3. ....

Also at a later stage one can couple this virtual model with the real world model in such a way that a movement done in the real warehouse by an individual will be updated in the model real time. This would be the ultimate challenge in implementing a VWMS.

With the latest technologies such as HTML5 3D rendering , AJAX , a framework which supports state-full user interfaces would help in implementing this.

Care must be taken in the areas such as performance , how to scale the system etc.

Note: VWMS is completely hypothetical concept where implementation is not promised, but with the technologies mentioned above an attempt can be made

Sunday, June 5, 2011

All I got is you!!!

When I see you
Every morning
with the cutest smile
In the world
I fall for you
day and day

When I see you
Sad and thoughtful
I loose my self
and talk too much
making it worst
all the times

That is for sure
I love you the most
That is for sure
I care you the most
I Will be next to you
Till my last breath

Monday, February 7, 2011

Going Technical .....Abstract Factory

Well , after taking a little break , here I am now again on the topic , GOF Design Patterns :). When I posted my first post related to design patterns I did not get any comments from my colleagues which made me to believe that no one interested in reading the blog :) haha..... By the way today one of my colleagues asked me if I made any new blog entries..great , now I know at least one person is reading the crazy stuff that I am putting here..well as long as there is one person who reads the blog , I would keep writing then ..:)

Last blog I explained what the Visitor pattern is and the intent of the pattern. Today lets talk about Abstract Factory pattern. If I ask someone how many design patterns he or she knows , this is one of the patterns which would always comes in the list of patterns that he or she remembers. But my honest question is , do you really understand the pattern and its usage or , you mention the pattern just because it is around you most frequently than others ? well which ever is your answer let me get into the ugly truth of this pattern :)

Lets begin with a simple examples , say you need to eat vegetables for your meal. You have two options either eat vegetable grown in INDIA or else eat vegetables grown in MALAYSIA. But you do not want to eat vegetables which are grown both INDIA and MALAYSIA at the same time. And also you have the freedom to change the country at any given time, for examples lets say you got sick of eating vegetables grown in INDIA then you can select vegetables grown in MALAYSIA from the next day.

Now lets say you need to store your vegetables in a safe place so that you can continue using those for daily food. In this case you would need some boxes in which you put different vegetables and then keep them in a store room which has a display board which you can use to show the current country. Now how are you going to keep track of which box contains which vegetables? well we could write the names of the vegetable outside the box so that we know what ever is inside is of the type that is written there. For examples if you use Carrot , Long Beans and Potatoes you would need three boxes and you would write down the names outside the box like "Carrot" , "Long Beans" , "Potatoes". Also the room in which you have kept these boxes is your "Store Room". Whenever you need to cook your food , what you do is simply go to the store room and then get some of Carrot from the box where there is Carrot , some of Long Beans from the box where there is Long Beans and some of Potatoes from the box where there is Potatoes.

When selecting the vegetable you do not worry about from which country they are because you are already aware of the country which is in the display board. On the other hand whenever you change the country you are NOT changing your Store room , neither the Boxes , all you change is the stuff inside the box and the name in the display board. So lets think that you need to use another country , say VIETNAM all you need to change is the name in the display board and stuff inside the boxes. You can continue to use your store room and boxes. Ok , how this thing is ever going to be related to Abstract Factory pattern ? aha .. the whole scenario represents a pretty good usage of the pattern. Lets look at the definition of this pattern "Abstract Factory is used to abstract away the creation of families of related objects without specifying the concrete classes"

The important words are "Families of related objects" and "Creation". well the word "Creation" is pretty straightforward but what about the other one "Families of related objects". This is equally important and you can not use Abstract Factory if the objects that are created do not belong to a single family and if they are in a way not related to each other. In above example the "Family" is VEGETABLE while all the vegetables are related to each other since they are just vegetables.

Now in the above example , the store room is similar to a Factory from which you get vegetables , so we can have a class which represents this store room , lets say the class is "AbstractVegetableFactory.java". And since we have a box which represents Carrots in general , lets have a class called "AbstractCarrot.java" , for the box which represents Long Beans in general lets have a class called "AbstractLongBean.java" and for the box which represents Potatoe in general lets have a class called "AbstractPotatoe.java". Now in the above example what we do is get carrot from the store room , so it is equivalent to getting an AbstractCarrot from AbstractVegetableFactory. So out implementation would be as follows,


package blog.gof.structural;

public abstract class AbstractVegetableFactory {

public abstract AbstractLongBean createAbstractLongBean();
public abstract AbstractPotatoe createAbstractPotate();
public abstract AbstractCarrot createAbstractCarrot();
}


package blog.gof.structural;

public abstract class AbstractLongBean {

}

package blog.gof.structural;

public abstract class AbstractPotatoe {

}

package blog.gof.structural;

public abstract class AbstractCarrot {

}

Well , the implementation above has abstracted the Vegetable family that we have been talking about so far. So when you need a Carrot all you do is first create an instance of the Factory and ask the factory to return a Carrot or any other type of vegetable supported by the factory itself. Now how we are going to make sure that whenever you need INDIAN vegetables that the returned vegetable is of INDIAN origin and whenever you need Malaysian vegetables that the returned vegetable is of MALAYSIAN origin. For that lets first assume INDIAN vegetables , lets say Carrot , we could have Indian Carrots which is represented by "IndianCarrot.java" who is extended from "AbstractCarrot.java"

package blog.gof.structural;

public class IndiaCarrot extends AbstractCarrot {

}

likewise ,

package blog.gof.structural;

public class IndianLongBean extends AbstractLongBean {

}

package blog.gof.structural;

public class IndianPotatoe extends AbstractPotatoe {

}

For vegetables of MALAYSIAN origin we could use a similar approach,

package blog.gof.structural;

public class MalaysianCarrot extends AbstractCarrot {

}

package blog.gof.structural;

public class MalaysianLongBean extends AbstractLongBean {

}

package blog.gof.structural;

public class MalaysianPotatoe extends AbstractPotatoe {

}

Ok, now we have represented different vegetables from different countries. But we still need factories which represents INDIAN vegetables factory and MALAYSIAN vegetable factory. Lets have IndianVegetableFactory.java which is extended from AbstractVegetableFactory.java to represent INDIAN vegetables

package blog.gof.structural;

public class IndianVegetableFactory extends AbstractVegetableFactory {

@Override
public AbstractCarrot createAbstractCarrot() {
return new IndiaCarrot();
}

@Override
public AbstractLongBean createAbstractLongBean() {
return new IndianLongBean();
}

@Override
public AbstractPotatoe createAbstractPotate() {
return new IndianPotatoe();
}

}

For MALAYSIAN vegetable factory we follow a similar approach ,

package blog.gof.structural;

public class MalaysianVegetableFactory extends AbstractVegetableFactory {

@Override
public AbstractCarrot createAbstractCarrot() {
return new MalaysianCarrot();
}

@Override
public AbstractLongBean createAbstractLongBean() {
return new MalaysianLongBean();
}

@Override
public AbstractPotatoe createAbstractPotate() {
return new MalaysianPotatoe();
}

}

Lets see the factories in action now ,

package blog.gof.structural;

public class PatternDemonstrationMain {

public static void main(String[] args) {

//Create a factory instance, the factory is now only returning
//objects which are produced in INDIA
AbstractVegetableFactory factory = new IndianVegetableFactory();
AbstractCarrot carrot = factory.createAbstractCarrot();
//Ok , the carrot created here is IDIAN carrot , because we are using
//INDIAN vegetable factory
//And same goes to potatoe and long beans as well
AbstractLongBean longbean = factory.createAbstractLongBean();
AbstractPotatoe potatoe = factory.createAbstractPotate();
//Now assume that one day you need to REUSE this piece of code
//You need to use vegetable factory , but this time the country is
//Malaysia.
//So how many lines of code you would change in this case to make this program
//work for Malaysia,
//Only one -->AbstractVegetableFactory factory = new IndianVegetableFactory();
//change the factory to be MalaysianVegetableFactoty and you are done
//you have abstracted the regional dependency and your code is verymuch reusable
//now
factory = new MalaysianVegetableFactory();
carrot = factory.createAbstractCarrot();
//Ok , the carrot created here is MALAYSIAN carrot , because we are using
//MALAYSIAN vegetable factory
//And same goes to potatoe and long beans as well
longbean = factory.createAbstractLongBean();
potatoe = factory.createAbstractPotate();

}

}

If you want to change the country from which you get your vegetables all you need to do is to replace the Factory with the correct factory implementation. Other than that you do not need to change anything else at all.

So basically the Abstract Factory pattern is useful when you have a Family of related objects to be created and if the objects that need to be created do not relate to each other then Abstract Factory is not a good choice.

If you think this post is useful you may comment on this , also if you need further assistance in understanding , you could also post your question as well...

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 expla...