ActionScript 3.0 Design Patterns

(Chris Devlin) #1
Key OOP Concepts Used with the Strategy Pattern | 401

function balloonAnimals( ) {
//balloon animal code
}
}

class Bojo extends Clown {
//Bojo unique
}

class Koka extends Clown {
//Koka unique
}

All the algorithms for juggling and making balloon animals are placed in the Clown


class. They’re passed on to the specific subclasses via inheritance. That works fine as


long as all the clowns can perform all the tricks. But what happens if one of the


clowns doesn’t know how to make balloon animals or juggle? Or what about a new


act being added? What will happen then?


So now, let’s encapsulate the algorithms in a Strategy object.


Encapsulated algorithms (pseudocode)


interface ClownTricks {
function someTrick( ): void;
}
class Juggle implements ClownTricks {
function someTrick( ): void {
//Juggling algorithm
}
}
class BalloonAnimals implements ClownTricks {
function someTrick( ): void {
//Making balloon animal algorithm
}
}

Now, using theClownclass as an aggregator, the program can delegate requests for


the different algorithms to the concreteClownsubclasses. If new tricks are intro-


duced, just implement them from theClownTricksinterface and use them as dele-


gates to theClownsubclasses that want to use them. (The actual application using


these concepts begins with Example 11-6.)


The encapsulated algorithms aren’t going to be very useful unless some object can


employ them. This is where delegation comes in, as you’ll see in the next section.


Using Delegation and Delegates


The Strategy design pattern is a perfect example of delegation. In delegation, two


objects are involved in handling a single request. One of the objects receives the


request and then delegates operations to adelegate. This is exactly what transpires

Free download pdf