"Mini Strategy" pattern using namespaces


/ Published in: ActionScript 3
Save to your folder(s)

I sometimes use namespaces to implements a sort of "mini strategy pattern."

This starts to pay off when you have more than one method that needs to do different things depending on the "mode" (or strategy). You have your "which mode am I on?" logic in one place (`set mode`) and then each mode-dependent method simply utilizes the `currentMode::someMethod()` technique.

Not as fancy, robust, or strict as a proper strategy pattern with interfaces and strategy objects, but if you want to keep things sort of self-contained, have a small amount of strategies to consider, or don't want the end user to have to worry about creating the strategy objects, then I've found this useful.


Copy this code and paste it in your HTML
  1. package {
  2. import flash.display.*;
  3.  
  4. public class NamespaceStrategy extends Sprite {
  5.  
  6. private var currentMode:Namespace;
  7. private namespace a;
  8. private namespace b;
  9.  
  10. public function NamespaceStrategy() {
  11. this.mode = "a";
  12. doSomething();
  13. this.mode = "b";
  14. doSomething();
  15. }
  16.  
  17. public function doSomething():void {
  18. currentMode::_doSomething();
  19. }
  20.  
  21. a function _doSomething():void {
  22. trace("A");
  23. }
  24.  
  25. b function _doSomething():void {
  26. trace("B");
  27. }
  28.  
  29. public function set mode(m:String):void {
  30. switch (m) {
  31. case "a":
  32. currentMode = a;
  33. break;
  34. case "b":
  35. currentMode = b;
  36. break;
  37. }
  38. }
  39. }
  40. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.