Couple of months ago i joined a high complexity project that a team of multiple developers were working on. This required some adjusting to my usual workflow, but it was for the better. I learned a lot and one of those things is a strategy pattern. This pattern goes well with pureMVC and definitely produces reusable code in the project. The core concept behind the pattern is to use a strategy object for every interface method that covers some group of actions. For example your object needs to flip on Y axis every click. This is how you would do this action in strategy pattern.

[cc lang=”actionscript”]package
{
/**
* …
* @author Martynas Bajoraitis
*/
public interface IFlip
{
function flip():void;
}

}[/cc]

now the strategy interface:
[cc lang=”actionscript”]package
{
/**
* …
* @author Martynas Bajoraitis
*/
public interface IFlipStrategy
{
function flip():void;
}

}[/cc]

now the strategy class itself
[cc lang=”actionscript”]package
{
import flash.display.DisplayObject;

/**
* …
* @author Martynas Bajoraitis
*/
public class FlipStrategy implements IFlipStrategy
{
private var _target:DisplayObject;
public function FlipStrategy(target:DisplayObject) {
_target = target;
}
public function flip():void {
_target.scaleY *= -1;
}
}

}[/cc]

and finally the implementation
[cc lang=”actionscript”]package
{
import flash.display.Sprite;

/**
* …
* @author Martynas Bajoraitis
*/
public class Flipper extends Sprite implements IFlip
{
private var _flipStrategy:IFlipStrategy;
public function Flipper() {
_flipStrategy = new FlipSptrategy(this);
}
public function flip():void {
_flipStrategy.flip();
}
}

}[/cc]

this example very crude and basic, but it shows the usability of strategy pattern. Using the strategy class i can extend every display object and make it to have the same action just by passing the right parameter to the strategy constructor

Categories: Blog

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload the CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.