Multiton

Actionscript:
  1. package {
  2.  
  3.     public class Multiton {
  4.        
  5.         public var test:String = "";
  6.        
  7.         private static  var _okToCreate:Boolean;
  8.         private static  var _instances:Object = new Object();
  9.         private static var _instanceNum:int = 0;
  10.  
  11.         public function Multiton() {
  12.             if (_okToCreate) {
  13.                 _instanceNum++;
  14.                 trace("created instance: " +_instanceNum);
  15.             } else {
  16.                 throw new Error(this + " is a Multiton... you must use the getInstance() method to instantiate it.");
  17.             }
  18.         }
  19.         public static function getInstance(key:String="default"):Multiton {
  20.             if (!_instances[key]) {
  21.                 _okToCreate = true;
  22.                 _instances[key] = new Multiton();
  23.                 _okToCreate = false;
  24.             }
  25.             return _instances[key];
  26.         }
  27.     }
  28. }

Holding off on the follow up to yesterdays post because I haven't finished it.... instead, here's a Multiton - Just like a Singleton but with multiple instances. You use it like this:

Actionscript:
  1. var m0:Multiton = Multiton.getInstance("one");
  2. m0.test = "i am instance one";
  3.  
  4. var m1:Multiton = Multiton.getInstance("two");
  5. m1.test = "i am instance two";
  6.  
  7. // elsewhere in the app
  8.  
  9. var multiton:Multiton = Multiton.getInstance("one");
  10. trace(multiton.test);
  11.  
  12. trace(Multiton.getInstance("two").test);

I've used this a few times and I seem to recall the Pure MVC makes use of this pattern (could be wrong about that though).

This entry was posted in OOP and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*