Saturday, September 05, 2009

Did you ever encounter issues while designing systems where more than one component is interacting with other component. If yes, the most obvious issue which you might have encountered would be the coupling issue. That is making one component interact with the other yet not making them know about others functioning. Well, today the pattern we would be talking about revolves around this issue. We are talking about command pattern.

Let us first understand what is command pattern. The formal definition is "Command Pattern encapsulates a request as an object, thereby letting us parametrize clients with different requests, queue or log request."
To understand it better, let us say that we would like to design a scheduler, which reads a request from a queue and process each until the queue is not empty. And possible requests includes:
a) Order request holds data to be written in database if the request is for an order performed.
b) If request pertains to weather reporting tool, it requests a weather class to return current temperature from a data source and then finally writing the data to a remote socket.
c) If request pertains to a third party tool, it reads its DB and creates a connection to a remote server and writes the requested data.

And for performing such operation we already have specific request classes available.
As you can see each of these request is of very different type. And we would not like scheduler to practically verify the request type and then invoke each classes pertaining to the actual request. If we do so, we would be increasing the coupling between scheduler and the request classes.

This seems to be the classic case where we can apply command pattern. Let us jump into this then without wasting any more time.

Well let us see which all classes are available for above requests:

a) Order class which allows setting an Order ID and then making a call to UpdateDB() which updates the DB using the Order ID.

b) For weather reporting a class named WeatherManagement is available, which exposes methods to read data from a component and then finally sending the data to remote client.

c) For third party tool, a class named ThirdPartyToolManagement class is avaiable which allow reading data from DB and then posting the data to an address.

Well, as you have seen we do not want scheduler to directly use these classes, we are going to apply the pattern.

The steps to apply command pattern in our case are as follows:

1. All command object will require to apply a single standard so let us define an interface named Command with a method declared Execute()

2. The actual command needs to implement the interface so that pur scheduler can make call to a single method irrespective of command. The possible commands in our case are
a) OrderCommand



So each of these will require implementing the inteface we defined above.

So let us see one of these classes:

public class OrderCommand implements Command
Order objOrder; //this is reference to the class which was supplied for order management

public OrderCommand(Order objOrd)
objOrder = objOrd;

public void Execute()

Similarly each of the other commands can be defined.

3. Allowing the scheduler to set the command. For this let us define our Scheduler class, using the one command we have seen for our complete understanding

public class Scheduler
Command objCmd;

public void SetCommand(Command objCommand)
objCmd = objCommand;

public void ExecuteScheduler()

Let us put this to a trial run:

public class TrailScheduler
public static void main(String args[])
Schduduler objScheduler = new Scheduler();

Order objOrder = new Order(); //creating an instance of actual receiver

objOrder.SetOrderID(12); //set the order Id on which operation is to take place

OrderCommand objOrdCmd = new OrderCommand(objOrder); //creating a command and wrapping the order instance

objScheduler.SetCommand(objOrdCmd);//setting the command finally in the scheduler


This is explain the functioning, though in reality a Scheduler will be dynamic and will not be static as shown here.

But what we have just seen is a single command. In reality Scheduler will have to deal with multiple command. So the command instance will be an array of commands and scheduler will serially loop though them and execute the command. And in reallity a Scheduler will be a daemon let us dress it up like that

public class Schedueler
Command[] aObjCmd;

public void Scheduler()
aObjCmd = new Command[10];
Command nullCmd = new nullCommand();

for(int i = 0; i < 10; i++)
aObjCmd[i] = nullCmd;

private void RetrieveNSetCommand()
aObjCmd = GetDataFromSource(); //this retrieve the ready command objects from a source

public void ExecuteScheduler()
while(true) //make it infinite
RetrieveNSetCommand(); //this loads all command from a source

for(int i = 0; i < 10; i++)
aObjCmd[i].Execute(); //execute each of the retrieved commands

Refer to the class diagram below for details.

As you have seen we have decoupled the scheduler from the actual request it is making. Now our scheduler no more worry about the actual command it is processing. All it knows is it is required to make a call to Execute() method and that's all.

If you need any clarification, please write to me.

Labels: , , , , ,

Perfect! But I have one doubt in this...could you plz explain me...
What is this RetrieveNSetCommand() method? From where does it load those commands...I mean who is responsible to load those?
Hi Kevin,
The RetrieveNSetCommand() method is expected to load all required commands from a helper source. For example, Scheduler class could make a static call to a method which identifies the commands to feed into the scheduler...this way scheduler is not required to know about those command and yet execute the commands..Please let me know, if you need any further clarifications..
sultry dating [url=]ireland dating[/url] alternative personals dating flash game online
custom auto audio systems [url=]auto dvd video[/url] dual screen auto dvd player auto audio capasiters
venice florida auto audio installation [url=]chrysler car audio[/url] custom auto audio systems d mercedes benz reviews auto extended warranty car audio and
car audio systems integrated ford falcon [url=]auto audio harness met809220[/url] car audio 1995 infiniti j30 repair chrysler car audio
increase blood flow medicine [url=]aciclovir[/url] generic viagra caverta cialis edegra kamagra meltabs penegra pacific springs dental omaha
hcg drug [url=]fluoxetine[/url] how to insert the penis in to the vagina [url=]shoot supplies[/url]
pain and blood pressure [url=]bupropion[/url] cost of medical has changed drug centers
japanese natural ways to increase breast size [url=]shallaki[/url] berkeley county wv health dept [url=]student activity on mineral ores[/url]
submarines drug [url=]cytoxan[/url] kitsap county health dept dental work at temple university
prescription fat pills [url=]ipnoterapia[/url] womens diet pill [url=]application of medical lasers[/url]
oregon health sciences pay [url=]study habits[/url] oreillys pharmacy clonmel democratic health policy staffers
urinalysis drug testing [url=]fml forte[/url] pulled calf muscle remedies [url=]meal planning balanced diet post op[/url]
[url=]cialis news[/url] internet pharmacy bulletin boards [url=]atacand plus[/url]
pharmacy schools in united states
[url=]times pharmacy kailua[/url] tebya v tbilisi karoshi esli ni drug xatiabi karoshi znakomi [url=]children spider bites and antibiotic treatment[/url]
does the use of marijuana lead to the use of hard drugs
[url=]movie drugstore cowboy[/url] pharmacy tech jobs in dayton ohio area [url=]new england journal of medicine aricept[/url] types of drug store [url=]bacteria[/url]
[url=]p141 erectile dysfunction drug[/url] lescol xl and erectile dysfunction [url=]diet drug acomplia[/url]
mexico pharmacy price modafinil
[url=]price schedule for medicare prescription drug legislation[/url] compare drug store prices [url=]amaryl[/url]
genreic drugs
[url=]drug free allergy medicine for dogs[/url] diabetes and drug screens [url=]what is the maximum daily dosage of vitamin d[/url] what is the drug senekot [url=]dramatic tapering of doxepin[/url]
[url=]debating about drug test in school[/url] zegen drug [url=]clarithromycin bronchitis[/url]
pharmacy rep
[url=]psychoactive drug list[/url] risperdal online pharmacy [url=]fluoxetine overdose cused parkinsonism[/url]
health benefits participants in volunteer work
[url=]drug abuse by teens[/url] virtual books on teen drug abuse [url=]fougera fluocinolone acetonide[/url] say yes to life drug ad [url=]flomax alternatives[/url]
state travel warnings gooseneck rv travel trailers in wisconsin
[url=]travel vacation flights[/url] australia byron travel [url=]santa maria travel[/url]
hopkins travel clinic
[url=]constant temperature travel mug[/url] patrick air force base passenger travel [url=]hotel charme[/url]
louisiana travel guide freeport travel trailers [url=]expedia vouchers free[/url]
lakeview auto washington state law on automobile sales
[url=]walmart automobile service[/url] auto accident witness interview [url=]jacks pontiac engine building tips[/url]
volkswagen t5 california solar panels uk
[url=]sioux city automobile dealer[/url] auto show columbus ohio [url=]donal and nancy panoz[/url]
new jersey personal auto insurance plan
[url=]tail lights for a mercedes clk 320[/url] mercedes benz direct london [url=]nissan r35 gt r[/url]
job novica opening travel huntsville travel
[url=]punta cana all inclusive travel reviews[/url] best discount travel [url=]international flight consolidator[/url]
washington state travel time
[url=]vina world travel visa[/url] nebraska travel guide state government [url=]alaska airline discount code[/url]
travel vacations 3rose peru travel precautions [url=]tucson airport shuttle service[/url]
merges and acquisitions in automobile industry eje delantero volkswagen escarabajo
[url=]volkswagen trike plans[/url] renewing automobile tag gulfport mississippi [url=]avidemux smart copy[/url]
automobile manufacturer size
[url=]wholesale domestic auto parts[/url] schematics for dodge ram sw 1997 [url=]early alfa romeo gtv[/url]
advance auto parts san antonio
[url=]drag racing nhra books[/url] enclosed auto trailer companies [url=]upgrades on 04 saleen[/url]
deer stage shoes tv discount designer prom dresses [url=]plus size designercocktail dresses[/url] payless shoes when to get new running shoes [url=]fort worth shoes[/url]
beach designer dress wedding remove detergent from clothes quickly [url=]dog clothes for small dogs[/url] cool boys clothes joe klein real estate tallman ny [url=]barbie fashion bag[/url]
body building clothes man privo shoes [url=]how to get bicycle chain grees out of clothes[/url] designer checks homepage southwestern clothes [url=]runnig clothes[/url]
two hearts maternity clothes merrell world leader shoes [url=]party designers in seattle wa[/url] z coil shoes discount puma shoes limited editions [url=]lauren conrad[/url]
english hentai comic
[url=]virtual adult world sex online[/url] sexy thong whore [url=]private family incest[/url]
hentai porn cartoon trailer
[url=]shooting an adult film[/url] free hentia porn videos [url=]harem hentai[/url]
hentai mp4 video downloads
[url=]dildo sex for guys[/url] standing tall 9 inch dildo [url=]free british mature upslirt[/url]
free celberty porn
[url=]hot sexy teen porn videos[/url] italian comic book porn 199 [url=]explicit gay pictures[/url]
about schmidt movie [url=]Species The Awakening[/url] free movie of erica boyer [url=]Terrors Advocate[/url]
legend of sleepy hollow the movie [url=]Ek Hasina Thi[/url] cb4 movie chris roc rapidshare [url=]Talk To Me[/url]
movie ringtones [url=]Pather Panchali[/url] movie times for michael clayton 28791 [url=]Face Off[/url]
microcasm of nature movie [url=]Tudo Sobre Minha Mae[/url] torrent files movie download [url=]Rambo IV[/url]
fashion search results msn encarta matt and lauren harris [url=]buy gucci watcg[/url] lauren lee smith cool boys clothes [url=]clothes female want nude male[/url]
adidas shoes for sale faber snowshoes [url=]aluminum furniture designer[/url] roper shoes working conditions in the fashion disging industry [url=]clothing add designer[/url]
smoking soda can [url=]cardura[/url] avadair astma medicine
female health and clothing [url=]indinavir[/url] heart 2 heart international ministries [url= ]sick after taking vitamin pills [/url] preventing hair loss
moore medical center [url=]imodium[/url] ulcer blood pressure
heating breast milk [url=]erectile dysfunction[/url] weight loss courses in florida [url= ]print out workout muscle [/url] philadelphia medical examiners building
[url=]antiepileptic drugs[/url] national institute for drug and alcohol abuse [url=]how much strain does pregnancy put on the kidneys[/url]
what drugs will make me lactate
[url=]online drug pharmacology dictionary[/url] new drug for leukemia sufferers [url=]xanax generic[/url]
taking prescription drugs with cirrhosis
[url=]purchase paroxetine pharmacy rx on line[/url] uninformed drug test [url=]mefloquine[/url] viagra homepage [url=]tramadol with sertraline[/url]
address for the lottery commission online casinos keno mini online
[url=]slot machine gambling tips[/url] flopowerball lottery [url=]betting tips[/url]
mass lottery daily numbers
[url=]austria lottery[/url] divination using ordinary playing cards [url=]ocean world dventure park casino and marina[/url]
the little creek casino trump plaza casino and hotel [url=]roulette wheel drawing[/url]
backup camera for automobile dodge gpm
[url=]automobile car coasters[/url] where to findpaint code for 2002 mercedes kompressor [url=]where do i fill the coolant on a 2001 jeep cherokee[/url]
game cheats grand theft auto san andrea
[url=]automobile insurance houston[/url] web surfing while travelling automobile [url=]mercedes crossover[/url]
mercedes vans
[url=]mercedes steering gear[/url] mercedes benz massapequa new york [url=]chrysler[/url]
[url=]newsletter viagra[/url] good price pharmacy brisbane [url=]anastrozole[/url]
costs of drug manufacturing
[url=]the buy cialis[/url] drug treatment richmond va [url=]pyridium[/url]
prednisone and xanax drug interaction
[url=]illegal performance enhancing drugs[/url] does going to jail help people that had drug addiction [url=]doxepin for itchy skin[/url] drug augment benzo withdrawal [url=]dosage of ramipril[/url]
casino island beach blanket bingo
[url=]best casino slot machines[/url] online betting websites live streaming [url=]cny casino[/url]
husband gambling bankruptcy
[url=]buy unlocked blackjack 2[/url] penna powerball lottery [url=]mexican playing cards[/url]
navajo casino twin arrows apple lottery online uk [url=]environmental bingo[/url]
[url=]mothers against drug driving[/url] drugs in the prison systems [url=]cialis drug drug drug drug levitra pharmacist prescription[/url]
health insurance fraud and abuse prepay review
[url=]compound pharmacy hormone therapy[/url] canadian pharmacy no perscription xanax [url=]proof of benzo in soma[/url]
urine drug test for morphine
[url=]drug stores for sale[/url] peer support drugs [url=]pamelor for pain[/url] drug manufacturing flowsheet canada [url=]breeding dog pheromone[/url]
fantasy lottery winning at keno
[url=]pool room trivia jackpot questions blog[/url] fundraiser betting boards [url=]slots vgi eprom chips[/url]
bingo halls essex
[url=]aston villa lottery[/url] qeii home lottery [url=]harrahs casino hotel kansas city[/url]
riverwind casino events reading and the california lottery [url=]baccarat crystal great uk deals[/url]
women bodybuilding competition [url=]french red wine[/url] easy ways to big breast dosage baytril dog
restriction modification in bacteria pdf [url=]gastrointestinale[/url] brewleys tea [url=]medicine list to increase sex need for female[/url]
fairfield commons movie theater [url=]drop dead diva[/url] kids make movie about bullying major league the movie
movie theaters in cary nc [url=]money talks[/url] edit quicktime movie pc pictues from the movie ice age the first movie
free beastiality movie clips [url=]out of time[/url] title of the movie is the guardian
invisible movie [url=]the good german[/url] lowes movie theatre frisco kid movie
nightvision movie [url=]the caretaker[/url] movie guide wellington new zealand borat movie review
movie slip ups [url=]gospel hill[/url] chain lightning movie review equestrian movie auditions
top 100 movie quotes [url=]carolina moon[/url] clips from the movie spin city edwards movie theatres
movie lucky one [url=]vanity fair[/url] babe movie
august rush the movie [url=]drive by chronicles sidewayz[/url] movie pacific heights copycat villians name of old comedy movie featuring women robbing mall
wifey world movie clips [url=]charlie and the chocolate factory[/url] new movie brad pitt decon movie company
download free simpsons the movie [url=]blown away[/url] jack black mos def movie clip coolidge corner movie theater brookline ma
amc movie theater in new jersey [url=]narrow margin[/url] nancy drew movie trtailer movie 300 sex scene
transpotting movie [url=]the jewel of the nile[/url] the guardian movie
background music movie sounds [url=]pygmalion[/url] ampland movie bandits movie cast
questions from the movie rudy [url=]heart of america[/url] dumbo movie theme movie love song
free music and lyrics movie torrent file [url=]drugstore cowboy[/url] blockbuster movie hits the rave movie theater
harry potter and the order of the phoenix full movie on line [url=]immer nie am meer[/url] how to price horror movie collectibles watch transformer animated movie online
online satellite movie channels like vox [url=]the adventures of andr and wally b [/url] windows movie maker menu style
female sqirt movie free [url=]joseph king of dreams[/url] nothing is private movie bittorrent who to contact to make a lifetime movie
movie theaters in louisville kentucky [url=]mistresses[/url] review movie premonition movie parasite
Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?