« March 2005 | Inicio | May 2005 »

April 26, 2005

An example of the Command Pattern

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 ):

interface ISoldierActions { public function destroy( ); public function moveTo( ); public function waitForMoreOrders( ); } class SoldierRole extends Role implements ISoldierActions { private var subject: IBasicActions; function SoldierRole( subject: IBasicActions ) { this.subject = subject; trace( "SoliderBehaviour created" ); } public function destroy( ) { //Specific behaviour trace( "Soldier interface. destroy" ); //Uses some of the animal's methods subject.eat( ); } public function moveTo( ) { //Specific behaviour trace( "Soldier Interface. moveTo" ); //Uses some of the animal's methods subject.moveLegs( ); } public function waitForMoreOrders( ) { trace( "Beeeee, I'll wait for more orders" ); } }

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 static function attack( soldiers: Array, peasants: Array ) { var numSoldiers: Number = soldiers.length; var numPeasants: Number = peasants.length; for( var i=0; i< numSoldiers / 2; i++ ) { soldiers[ i ].destroy( ); } for( var i=numSoldiers/2; i< numSoldiers; i++ ) { soldiers[ i ].waitForMoreOrders( ); } for( var i=0; i< numPeasants / 2; i++ ) { peasants[ i ].doGardening( ); } for( var i=numPeasants/2; i< numPeasants; i++ ) { peasants[ i ].driveTo( ); } } }

And in the first frame of the main timeline:

var soldiers: Array = new Array( ); var peasants: Array = new Array( ); for( var i=0; i<10; i++ ) { var sheep: Sheep = new Sheep( ); sheep.addExtension( "SoldierRole", new SoldierRole( sheep ) ); var soldierSheep: ISoldierActions = ISoldierActions( sheep.getExtension( "SoldierRole" ) ); soldiers.push( soldierSheep ); } for( var i=10; i<20; i++ ) { var sheep: Sheep = new Sheep( ); sheep.addExtension( "PeasantRole", new PeasantRole( sheep ) ); var peasantSheep: IPeasantActions = IPeasantActions( sheep.getExtension( "PeasantRole" ) ); peasants.push( peasantSheep ); } ProfessorCoupling1.attack( soldiers, peasants );

( 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:

interface ICommandActions { public function execute( ); }

And the different commands will be:

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

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

class ProfessorCoupling { public static function attack( commandsArray: Array ) { for( var k=0; k< commandsArray.length; k++ ) { commandsArray[ k ].execute( ); } } }

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

var theArmy: Array = new Array( ); for( var i=0; i<5; i++ ) { var sheep: Sheep = new Sheep( ); sheep.addExtension( "SoldierRole", new SoldierRole( sheep ) ); var soldierSheep: ISoldierActions = ISoldierActions( sheep.getExtension( "SoldierRole" ) ); var saCommand: SoldierAttack = new SoldierAttack( soldierSheep ); theArmy.push( saCommand ); } for( var i=5; i<10; i++ ) { var sheep: Sheep = new Sheep( ); sheep.addExtension( "SoldierRole", new SoldierRole( sheep ) ); var soldierSheep: ISoldierActions = ISoldierActions( sheep.getExtension( "SoldierRole" ) ); var swCommand: SoldierWait = new SoldierWait( soldierSheep ); theArmy.push( swCommand ); } for( var i=10; i<15; i++ ) { var sheep: Sheep = new Sheep( ); sheep.addExtension( "PeasantRole", new PeasantRole( sheep ) ); var peasantSheep: IPeasantActions = IPeasantActions( sheep.getExtension( "PeasantRole" ) ); var paCommand: PeasantAttack = new PeasantAttack( peasantSheep ); theArmy.push( paCommand ); } for( var i=15; i<20; i++ ) { var sheep: Sheep = new Sheep( ); sheep.addExtension( "PeasantRole", new PeasantRole( sheep ) ); var peasantSheep: IPeasantActions = IPeasantActions( sheep.getExtension( "PeasantRole" ) ); var pdCommand: PeasantDrive = new PeasantDrive( peasantSheep ); theArmy.push( pdCommand ); } ProfessorCoupling.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...

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

April 06, 2005

An example of the Extension Objects pattern ( the java version )

Do you remember Professor Coupling?. Do you remember his evil plans to conquer the world?.

Today, we’ll see how the Extension Objects pattern ( or “how to change the interface that a class implements at runtime” ) has helped Professor Coupling. It won’t be an easy task, because this is a complex pattern, but who said that being an evil genius was easy?.

If you remember the last post, Professor Coupling designed a cloning machine that was able to clone any given animal, without knowing it’s race ( or type ), just delegating the creation details to the animal itself.

So that’s the point where our story starts today. Professor Coupling has cloned yet ten thousand sheeps, and nine thousand cows ( he said something like “that’s the exact number I need, muhahahahahahhhhaaaaaa” ). But suddenly, he realizes that he is going to need a lot of sheeps, yes, and a lot of cows, but not all the sheeps nor all the cows will have the same role. Why?. Well, conquering the world is not easy. You need to organize things very well. You need a plan ( an evil plan ).

And Professor Coupling has a plan. He wants to train some of the sheeps, and some of the cows, as his army. He wants them to kill, without asking questions ( sorry for the violence, that’s what happens when you are crazy ). But he also wants some of the sheeps and cows to work in the factories, building weapons. And he also needs some of those sheeps and cows working in the countryside, growing vegetables to feed his army ( remember, Professor Coupling is crazy, but the is not an idiot ). He needs to assign different roles to the clones he has created.

soldierSheep.jpg
A SoldierSheep. No comment.

[Note]. Just to keep the different posts separated, each one showing an example of a pattern and only a pattern, I will start writing the Sheep and Cow classes from scratch. But, Professor Coupling will just add the new code to those classes.

So, the evil genius starts to think: “Right, I have a class that represents a Sheep. And now I need a sheep that behaves like a soldier, and another one that behaves like a peasant, and the same with the cows.”. That sounds like extending the functionality of a class, doesn’t it. That’s exactly the same that Professor Couple thinks. Brilliant!!!. “I will write a SoldierSheep class that extends Sheep, and another class, PeasantSheep, that also extends Sheep” ( insert five minutes of hysterical laughs here ).

But before starting writing code, Professor Coupling notices that maybe that’s not the best solution, because anytime he wants to assign a new role to a Sheep, he will have to write a new subclass ( for instance, an EngineerSheep, or a MaitreSheep,… ). And he doesn’t know in advance which roles he will need to assign to a sheep. It all depends of what he needs in the future. He wants to support the addition of unforeseen interfaces to the Sheep class ( isn’t he a genius? ).

He also notices that this approach has another weak point. He will not be able to re-assign a role. If he creates a SoldierSheep, that will be a SoldierSheep forever, no matter if he needs it to grow onions ( he is crazy, remember, sometimes he has very strange ideas ).

He also notices another subtle weak point. A SoldierSheep and a Sheep are exactly the same: sheeps. The only difference is that one of them has a particular behaviour, but in essence, they are the same.

Professor Coupling is crazy, but he’s not an idiot ( I know, I know, you knew that ). So, he believes he has found enough weak points in his initial idea to start searching google for another solution.

peasantSheep.jpg
A PeasantSheep. Believe it or not, it's enjoying its spare time gardening!

And after a few attempts, he finds a book (Pattern Languages of Program Design, Volume 3, Addison-Wesley, 1998. ), where Erich Gamma ( yes, one of the GoF authors ) wrote a chapter about the Extension Objects pattern.

This pattern intents to anticipate the extension of an object’s interface in the future ( that means: new interfaces can be added to a class at runtime ).

So he starts reading, and laughing, And the more he reads, the more he laughs!!.

The idea is quite simple. A class ( Sheep ) will be able to change the interface it implements at runtime, selecting that interface from a collection of objects ( the Extension Objects ). Each one of those objects will encapsulate one of the roles ( SoldierSheep, PeasantSheep,… ). ( At this moment, Professor Coupling has been laughing for nearly twenty minutes!! ).

How will the Sheep class select the interface to implement?. And how will the Cow class do it?. Well, both classes will implement the following interface:

public interface ISubject { public Role getExtension( String extName ); }

The Sheep also implements an interface to encapsulate the actions it implements as an animal ( eat, moving the legs and arms… )

public interface IBasicActions { public void moveArms( ); public void moveLegs( ); public void eat( ); }

So, the Sheep class will be

public class Sheep implements ISubject, IBasicActions { private SoldierRole soldierRole; private PeasantRole peasantRole; public Sheep( ) { System.out.println( "I'm a sheep" ); } public Role getExtension( String extName ) { Role returnValue = null; if( extName.equals( "SoldierRole" ) ) { if( soldierRole == null ) { returnValue = new SoldierRole( this ); } else { returnValue = soldierRole; } } if( extName.equals( "PeasantRole" ) ) { if( peasantRole == null ) { returnValue = new PeasantRole( this ); } else { returnValue = peasantRole; } } return returnValue; } public void moveArms( ) { // movement implementation System.out.println( "the sheep moves one arm" ); } public void moveLegs( ) { // movement implementation System.out.println( "the sheep moves one leg" ); } public void eat( ) { // implements the way sheeps eat System.out.println( "munch. munch" ); } }

Notice how that class implements the getExtension method, choosing the class it should return from a collection of roles ( that are instance variables ). And the roles?

Here’s the base Role ( I have not implemented anything, but any common functionality to all the roles should be implemented here ).

public abstract class Role { }

So, the SoldierRole:

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

And the PeasantRole:

public class PeasantRole extends Role implements IPeasantActions { private IBasicActions subject; public PeasantRole( IBasicActions subject ) { this.subject = subject; System.out.println( "PeasantBehaviour created" ); } public void driveTo( ) { //Specific behaviour System.out.println( "I drive to " ); //Use some of the animal's methods subject.moveArms( ); subject.moveLegs( ); } public void doGardening( ) { //Specific behaviour System.out.println( "OK, gardening" ); //Use some of the animal's methods subject.moveArms( ); } }

Both classes ( SoldierRole and PeasantRole ) implement two different interfaces ( ISoldierActions and IPeasantActions ). Those are the interfaces that the Sheep class will seem to implement.

Look:

public class ProfessorCoupling { public static void main( String[ ] args ) { Sheep sheep = new Sheep( ); ISoldierActions soldierSheep = ( ISoldierActions ) sheep.getExtension( "SoldierRole" ); soldierSheep.destroy( ); IPeasantActions peasantSheep = ( IPeasantActions ) sheep.getExtension( "PeasantRole" ); peasantSheep.doGardening( ); } }

( Insert thirty minutes of hysterical laughs here ). But, hey!!. Wait!!. Professor Coupling has noticed a little problem ( well, it’s not a problem, really, it’s a “difficult solution” ).

The Sheep class knows its extensions ( the roles ). Those extensions are stored in instance variables, so there’s no way to add or remove extensions at runtime.

So he decides to refactor his Sheep class. This class will no longer store its possible extensions in instance variables, but it will manage a collection ( a HashMap, an Object ) that will store them. So, it will be possible to add or remove extensions whenever it’s needed. ( you wouldn’t believe how he’s laughing now ).

So, he refactors the ISubject interface:

public interface ISubject { public Role getExtension( String extName ); public void addExtension( String extName, Role extension ); public void removeExtension( String extName ); }

And the Sheep class ( I don't like the way I've implemented the collection, using an object, but ... )

import java.util.HashMap; public class Sheep implements ISubject, IBasicActions { private HashMap rolesCol; public Sheep( ) { System.out.println( "I'm a sheep" ); rolesCol = new HashMap( ); } public Role getExtension( String extName ) { return ( Role ) rolesCol.get( extName ); } public void addExtension( String extName, Role extension ) { rolesCol.put( extName, extension ); } public void removeExtension( String extName ) { rolesCol.remove( extName ); } public void moveArms( ) { // movement implementation System.out.println( "the sheep moves one arm" ); } public void moveLegs( ) { // movement implementation System.out.println( "the sheep moves one leg" ); } public void eat( ) { // implements the way sheeps eat System.out.println( "munch. munch" ); } }

And Professor Coupling can do something like:

public class ProfessorCoupling { public static void main( String[ ] args ) { Sheep sheep = new Sheep( ); sheep.addExtension( "SoldierRole", new SoldierRole( sheep ) ); ISoldierActions soldierSheep = ( ISoldierActions ) sheep.getExtension( "SoldierRole" ); soldierSheep.destroy(); sheep.removeExtension( "SoldierRole" ); sheep.addExtension( "PeasantRole", new PeasantRole( sheep ) ); IPeasantActions peasantSheep = ( IPeasantActions ) sheep.getExtension( "PeasantRole" ); peasantSheep.doGardening( ); } }

So, the clones created by the cloning machine are able to change the way we look at them at runtime ( first they can be soldiers, then they can be peasants, then whatever role Professor Coupling wants ). He has kept the Sheep abstraction unpolluted with operations that are specific to a client. He could have done so subclassing, defining the client operations in those subclasses, but that will create a hierarchy too difficult to manage.

The next Professor Coupling’s adventure will be easier to follow, I promise. Even evil geniuses need some vacations!.

[Important note]. Some self-criticism. The code that retrieves the roles won’t pass any quality check. Using a string as a key value to set and get those roles is very dangerous.

An example of the Extension Objects pattern

Do you remember Professor Coupling?. Do you remember his evil plans to conquer the world?.

Today, we’ll see how the Extension Objects pattern ( or “how to change the interface that a class implements at runtime” ) has helped Professor Coupling. It won’t be an easy task, because this is a complex pattern, but who said that being an evil genius was easy?.

If you remember the last post, Professor Coupling designed a cloning machine that was able to clone any given animal, without knowing it’s race ( or type ), just delegating the creation details to the animal itself.

So that’s the point where our story starts today. Professor Coupling has cloned yet ten thousand sheeps, and nine thousand cows ( he said something like “that’s the exact number I need, muhahahahahahhhhaaaaaa” ). But suddenly, he realizes that he is going to need a lot of sheeps, yes, and a lot of cows, but not all the sheeps nor all the cows will have the same role. Why?. Well, conquering the world is not easy. You need to organize things very well. You need a plan ( an evil plan ).

And Professor Coupling has a plan. He wants to train some of the sheeps, and some of the cows, as his army. He wants them to kill, without asking questions ( sorry for the violence, that’s what happens when you are crazy ). But he also wants some of the sheeps and cows to work in the factories, building weapons. And he also needs some of those sheeps and cows working in the countryside, growing vegetables to feed his army ( remember, Professor Coupling is crazy, but the is not an idiot ). He needs to assign different roles to the clones he has created.

soldierSheep.jpg
A SoldierSheep. No comment.

[Note]. Just to keep the different posts separated, each one showing an example of a pattern and only a pattern, I will start writing the Sheep and Cow classes from scratch. But, Professor Coupling will just add the new code to those classes.

So, the evil genius starts to think: “Right, I have a class that represents a Sheep. And now I need a sheep that behaves like a soldier, and another one that behaves like a peasant, and the same with the cows.”. That sounds like extending the functionality of a class, doesn’t it. That’s exactly the same that Professor Couple thinks. Brilliant!!!. “I will write a SoldierSheep class that extends Sheep, and another class, PeasantSheep, that also extends Sheep” ( insert five minutes of hysterical laughs here ).

But before starting writing code, Professor Coupling notices that maybe that’s not the best solution, because anytime he wants to assign a new role to a Sheep, he will have to write a new subclass ( for instance, an EngineerSheep, or a MaitreSheep,… ). And he doesn’t know in advance which roles he will need to assign to a sheep. It all depends of what he needs in the future. He wants to support the addition of unforeseen interfaces to the Sheep class ( isn’t he a genius? ).

He also notices that this approach has another weak point. He will not be able to re-assign a role. If he creates a SoldierSheep, that will be a SoldierSheep forever, no matter if he needs it to grow onions ( he is crazy, remember, sometimes he has very strange ideas ).

He also notices another subtle weak point. A SoldierSheep and a Sheep are exactly the same: sheeps. The only difference is that one of them has a particular behaviour, but in essence, they are the same.

Professor Coupling is crazy, but he’s not an idiot ( I know, I know, you knew that ). So, he believes he has found enough weak points in his initial idea to start searching google for another solution.

peasantSheep.jpg
A PeasantSheep. Believe it or not, it's enjoying its spare time gardening!

And after a few attempts, he finds a book (Pattern Languages of Program Design, Volume 3, Addison-Wesley, 1998. ), where Erich Gamma ( yes, one of the GoF authors ) wrote a chapter about the Extension Objects pattern.

This pattern intents to anticipate the extension of an object’s interface in the future ( that means: new interfaces can be added to a class at runtime ).

So he starts reading, and laughing, And the more he reads, the more he laughs!!.

The idea is quite simple. A class ( Sheep ) will be able to change the interface it implements at runtime, selecting that interface from a collection of objects ( the Extension Objects ). Each one of those objects will encapsulate one of the roles ( SoldierSheep, PeasantSheep,… ). ( At this moment, Professor Coupling has been laughing for nearly twenty minutes!! ).

How will the Sheep class select the interface to implement?. And how will the Cow class do it?. Well, both classes will implement the following interface:

interface ISubject { public function getExtension( extName: String ): Role; }

The Sheep also implements an interface to encapsulate the actions it implements as an animal ( eat, moving the legs and arms… )

interface IBasicActions { public function moveArms( ); public function moveLegs( ); public function eat( ); }

So, the Sheep class will be

class Sheep implements ISubject, IBasicActions { private var soldierRole: SoldierRole; private var peasantRole: PeasantRole; function Sheep( ) { trace( "I'm a sheep" ); } public function getExtension( extName: String ): Role { var returnValue: Role = null; if( extName == "SoldierRole" ) { if( soldierRole == null ) { returnValue = new SoldierRole( this ); } else { returnValue = soldierRole; } } if( extName == "PeasantRole" ) { if( peasantRole == null ) { returnValue = new PeasantRole( this ); } else { returnValue = peasantRole; } } return returnValue; } public function moveArms( ) { // movement implementation trace( "the sheep moves one arm" ); } public function moveLegs( ) { // movement implementation trace( "the sheep moves one leg" ); } public function eat( ) { // implements the way sheeps eat trace( "munch. munch" ); } }

Notice how that class implements the getExtension method, choosing the class it should return from a collection of roles ( that are instance variables ). And the roles?

Here’s the base Role ( I have not implemented anything, but any common functionality to all the roles should be implemented here ).

class Role { function Role( ) { } }

So, the SoldierRole:

class SoldierRole extends Role implements ISoldierActions { private var subject: IBasicActions; function SoldierRole( subject: IBasicActions ) { this.subject = subject; trace( "SoliderBehaviour created" ); } public function destroy( ) { //Specific behaviour trace( "Soldier interface. destroy" ); //Uses some of the animal's methods subject.eat( ); } public function moveTo( ) { //Specific behaviour trace( "Soldier Interface. moveTo" ); //Uses some of the animal's methods subject.moveLegs( ); } }

And the PeasantRole:

class PeasantRole extends Role implements IPeasantActions { private var subject: IBasicActions ; function PeasantRole( subject: IBasicActions ) { this.subject = subject; trace( "PeasantBehaviour created" ); } public function driveTo( ) { //Specific behaviour trace( "I drive to " ); //Uses some of the animal's actions subject.moveArms( ); subject.moveLegs( ); } public function doGardening( ) { //Specific behaviour trace( "OK, gardening" ); //Uses some of the animal's actions subject.moveArms( ); } }

Both classes ( SoldierRole and PeasantRole ) implement two different interfaces ( ISoldierActions and IPeasantActions ). Those are the interfaces that the Sheep class will seem to implement.

Look:

var sheep: Sheep = new Sheep( ); var soldierSheep: ISoldierActions = ISoldierActions( sheep.getExtension( "SoldierRole" ) ); soldierSheep.destroy( ); var peasantSheep: IPeasantActions = IPeasantActions( sheep.getExtension( "PeasantRole" ) ); peasantSheep.doGardening( );

( Insert thirty minutes of hysterical laughs here ). But, hey!!. Wait!!. Professor Coupling has noticed a little problem ( well, it’s not a problem, really, it’s a “difficult solution” ).

The Sheep class knows its extensions ( the roles ). Those extensions are stored in instance variables, so there’s no way to add or remove extensions at runtime.

So he decides to refactor his Sheep class. This class will no longer store its possible extensions in instance variables, but it will manage a collection ( a HashMap, an Object ) that will store them. So, it will be possible to add or remove extensions whenever it’s needed. ( you wouldn’t believe how he’s laughing now ).

So, he refactors the ISubject interface:

interface ISubject { public function getExtension( extName: String ): Role; public function addExtension( extName: String , extension: Role ); public function removeExtension( extName: String ); }

And the Sheep class ( I don't like the way I've implemented the collection, using an object, but ... )

class Sheep implements ISubject, IBasicActions { private var rolesCol: Object; function Sheep( ) { trace( "I'm a sheep" ); rolesCol = new Object( ); } public function getExtension( extName: String ): Role { return rolesCol[ extName ]; } public function addExtension( extName: String, extension: Role ) { rolesCol[ extName ] = extension; } public function removeExtension( extName: String ) { rolesCol[ extName ] = null; } public function moveArms( ) { // movement implementation trace( "the sheep moves one arm" ); } public function moveLegs( ) { // movement implementation trace( "the sheep moves one leg" ); } public function eat( ) { // implements the way sheeps eat trace( "munch. munch" ); } }

And Professor Coupling can do something like:

var sheep: Sheep = new Sheep( ); sheep.addExtension( "SoldierRole", new SoldierRole( sheep ) ); var soldierSheep: ISoldierActions = ISoldierActions( sheep.getExtension( "SoldierRole" ) ); soldierSheep.destroy(); sheep.removeExtension( "SoldierRole" ); sheep.addExtension( "PeasantRole", new PeasantRole( sheep ) ); var peasantSheep: IPeasantActions = IPeasantActions( sheep.getExtension( "PeasantRole" ) ); peasantSheep.doGardening( );

So, the clones created by the cloning machine are able to change the way we look at them at runtime ( first they can be soldiers, then they can be peasants, then whatever role Professor Coupling wants ). He has kept the Sheep abstraction unpolluted with operations that are specific to a client. He could have done so subclassing, defining the client operations in those subclasses, but that will create a hierarchy too difficult to manage.

The next Professor Coupling’s adventure will be easier to follow, I promise. Even evil geniuses need some vacations!.

[Important note]. Some self-criticism. The code that retrieves the roles won’t pass any quality check. Using a string as a key value to set and get those roles is very dangerous.

April 03, 2005

[OT] The new member of the design-nation family

newton.jpg

Yes, it is a Newton ( a MessagePad 120 ) . And as you can see in the picture, it still works.

It's amazing to see how advanced was this device. It can work in portrait mode, it can be synchronized with a Mac or a PC, it supports PCMCIA cards...

And it's also amazing to see how devoted is the Newton's users community. There are a lot of active forums, e-mail lists, and websites devoted to this device.

newton_mini.jpg

newton_ipaq.jpg

Here are the hardware specs:

• Ram: 2mb
• Rom: 8mb(upgrade)
• Processor: ARM 610 20MHz
• Newton OS: 1.3, 2.0
• Screen: 320x240, no backlight
• Release: 11/95
• Extra Notes: NOS 2.0 would only run if the unit had a rom upgrade.

It's time to play with it a bit. Enjoy the sunday!