« An example of the Extension Objects pattern ( the java version ) | Inicio | An example of the Command Pattern »

An example of the Command Pattern ( the Java Version )

Everything is ready. The sheeps and the cows are cloned, and their roles have been assigned. It’s time for Professor Coupling to launch the final attack. It’s time to conquer the world!!!.

But how will Professor Coupling give his troops the order to launch the attack?.

If you remember the previous posts, Professor Coupling is able to clone any animal, and then, he is able to assign that cloned animal its role. So, Professor Coupling has cloned sheeps and cows, and now his army is composed of soldier sheeps, peasant sheeps, solider cows and peasant cows ( it’s not easy to conquer the world ).

Professor Coupling is crazy, but he’s not an idiot. He wants to conquer the world, sure, he has an evil plan to do it, sure, but he knows that having a good plan ( even if it’s an evil plan ) is not a guarantee to success. He needs an emergency plan.

He wants that some of the soldier sheeps take part in the first ( and glorious ) attack. But he wants some other soldier sheeps to rest while their mates die in the battlefield ( sorry again, this is very violent, I know, but, you know, he’s trying to conquer the world ), and to be ready to serve as reinforcements.

How could Professor Coupling manage this? Well, he is very busy, so the attack must be launched easily. Something like pressing the “attack” button will be perfect. It’s quick, it’s easy, and he can delegate the action of pressing the button to anyone of his subordinates ( muhahahahahahahaha ). That will be perfect, but only if he finds the way to tell every single Sheep what it is supposed to do when the "glorious moment" comes.

But how?. The knowledge that Professor Coupling has about the Soldier Sheeps is their interface. He knows that every soldier sheep implements and interface called ISoldierActions ( please, take a look at the post about the Extension Objects pattern, well need it ). What he really wants is that some sheeps execute one of the methods of ISoldierActions, and some sheeps execute a different one.

Let’s try to explain it with an example. Here are the ISoldierActions interface and the SoldierRole class ( they are a bit different from the ones that appeared in the last post ):

public interface ISoldierActions { public void destroy( ); public void moveTo( ); public void waitForMoreOrders( ); } public class SoldierRole extends Role implements ISoldierActions { private IBasicActions subject; public SoldierRole( IBasicActions subject ) { this.subject = subject; System.out.println( "SoliderBehaviour created" ); } public void destroy( ) { //Specific behaviour System.out.println( "Soldier interface. destroy" ); //Use some of the animal's methods subject.eat( ); } public void moveTo( ) { //Specific behaviour System.out.println( "Soldier Interface. moveTo" ); //Use some of the animal's methods subject.moveLegs( ); } public void waitForMoreOrders( ) { System.out.println( "I'll wait for more orders. Beeeeeee" ); } }

And here are IPeasantActions and PeasantRole are exactly as they were

So, Professor Coupling has cloned ten thousand Soldier Sheeps, and ten thousand Peasant Sheeps, and he uses two arrays to hold a reference to all of them.

So, when he presses the "attack" button, he could do something like:

class ProfessorCoupling { public ProfessorCoupling( ) { } public void attack( ISoldierActions[] soldiers, IPeasantActions[] peasants ) { int soldiersCount = soldiers.length; int peasantsCount = peasants.length; for( int idx=0; idx< soldiersCount / 2; idx++ ) { soldiers[ idx ].destroy( ); } for( int idx=soldiersCount/2; idx< soldiersCount; idx++ ) { soldiers[ idx ].waitForMoreOrders( ); } for( int idx=0; idx< peasantsCount / 2; idx++ ) { peasants[ idx ].doGardening( ); } for( int idx=peasantsCount/2; idx< peasantsCount; idx++ ) { peasants[ idx ].driveTo( ); } } }

( Insert some hysterical laughs here, please ). You know what comes now, don’t you?. Professor Coupling is crazy, but he’s not an idiot. He doesn’t like the solution he has found. Why?. Well, it’s not what he wanted. He just wanted to say "attaaaaaaaaaaaaaaaaaaaaaaack", and laugh hysterically while the sheeps obey his orders.

He feels that everything will be much easier if he could give every sheep an envelope containing its orders. When the moment of glory comes, he will just have to tell every sheep to open the envelope and obey the orders it contains. But he doesn’t what to know what he is requesting the sheep to do, and if fact, he doesn’t even what to know if he’s requesting something to a sheep or a cow, or whatever.

oveja_sobre.jpg

And then, he remembers when he was a young student, and read the GoF book. And he starts to laugh. He has remembered the Command Pattern.

He wants to give four different orders. Two of them will have to be obeyed by the Soldier Sheeps ( "attack", and "wait where you are until you receive more orders" ), and the other two by the Peasant Sheeps ( "start gardening", and "drive your truck home" ).

So he’s going to encapsulate the order, and the receiver of the order in a package ( the envelope ). How?. Look:

First of all, he will write the following interface:

public interface ICommandActions { public void execute( ); }

And the different commands will be:

public class SoldierAttack implements ICommandActions { ISoldierActions receiver; public SoldierAttack( ISoldierActions soldier ) { receiver = soldier; } public void execute( ) { receiver.destroy( ); } } public class SoldierWait implements ICommandActions { ISoldierActions receiver; public SoldierWait( ISoldierActions soldier ) { receiver = soldier; } public void execute( ) { receiver.waitForMoreOrders( ); } } public class PeasantAttack implements ICommandActions { IPeasantActions receiver; public PeasantAttack( IPeasantActions peasant ) { receiver = peasant; } public void execute( ) { receiver.doGardening( ); } } public class PeasantDrive implements ICommandActions { private IPeasantActions receiver; public PeasantDrive( IPeasantActions peasant ) { receiver = peasant; } public void execute( ) { receiver.driveTo( ); } }

So, now, when Professor Coupling presses the "attaaaaaaaaaaaaaaack" button, he will have to do something like:

public void attack( ICommandActions[] theArmy ) { int sheepsCount = theArmy.length; for( int idx=0; idx< sheepsCount; idx++ ) { theArmy[ idx ].execute( ); } }

That method receives as a parameter an array containing all the commands. That array could be built with a code similar to this:

public class ProfessorCoupling { public ProfessorCoupling( ) { } public void attack( ICommandActions[] theArmy ) { int sheepsCount = theArmy.length; for( int idx=0; idx< sheepsCount; idx++ ) { theArmy[ idx ].execute( ); } } public static void main( String[ ] args ) { Sheep sheep = null; ICommandActions[ ] theArmy = new ICommandActions[ 20 ]; ISoldierActions soldierSheep = null; IPeasantActions peasantSheep = null; SoldierAttack saCommand = null; SoldierWait swCommand = null; PeasantAttack paCommand = null; PeasantDrive pdCommand = null; for( int i=0; i<5; i++ ) { sheep = new Sheep( ); sheep.addExtension( "SoldierRole", new SoldierRole( sheep ) ); soldierSheep = ( ISoldierActions ) sheep.getExtension( "SoldierRole" ); saCommand = new SoldierAttack( soldierSheep ); theArmy[ i ] = saCommand; } for( int i=5; i<10; i++ ) { sheep = new Sheep( ); sheep.addExtension( "SoldierRole", new SoldierRole( sheep ) ); soldierSheep = ( ISoldierActions ) sheep.getExtension( "SoldierRole" ); swCommand = new SoldierWait( soldierSheep ); theArmy[ i ] = swCommand; } for( int i=10; i<15; i++ ) { sheep = new Sheep( ); sheep.addExtension( "PeasantRole", new PeasantRole( sheep ) ); peasantSheep = ( IPeasantActions ) sheep.getExtension( "PeasantRole" ); paCommand = new PeasantAttack( peasantSheep ); theArmy[ i ] = paCommand; } for( int i=15; i<20; i++ ) { sheep = new Sheep( ); sheep.addExtension( "PeasantRole", new PeasantRole( sheep ) ); peasantSheep = ( IPeasantActions ) sheep.getExtension( "PeasantRole" ); pdCommand = new PeasantDrive( peasantSheep ); theArmy[ i ] = pdCommand; } ProfessorCoupling professor = new ProfessorCoupling( ); professor.attack( theArmy ); } }

That code was awful, but it serves its purpose, which is to show how Professor Coupling has created a collection of objects, each one encapsulating a command and the receiver of that command. Now, Professor Coupling doesn’t need to know anything about the commands or about the receiver of those commands. He just has to say "hey, command, execute yourself", and the command will do the rest.

In fact, Professor Coupling has been able to decouple three different process: the object creation ( implementing the prototype pattern ), the assignment of roles to those objects ( the extension objects pattern ), and the way that those roles are “executed” ( the command pattern ).

Maybe he’s really a genius...