Posted By

alejandromb on 12/20/09


Tagged

Singleton as3 actionscript3


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

tspitzr


AS3 | KCSingleton


 / Published in: ActionScript 3
 

URL: http://www.kirikacode.com

  1. package kc.core {
  2. import flash.errors.IllegalOperationError;
  3. import flash.utils.Dictionary;
  4.  
  5. public class KCSingleton extends Object {
  6.  
  7. // @const
  8.  
  9. public static const ERROR:String = "Illegal instantiation attempted on class of singleton type.";
  10.  
  11. // @private
  12.  
  13. private static var _records:Dictionary;
  14.  
  15. // @constructor
  16.  
  17. public function KCSingleton() {
  18. throw new IllegalOperationError( ERROR );
  19. }
  20.  
  21. // @methods
  22.  
  23. public static function register( api:String, value:Class ):void {
  24. if( _records == null ) {
  25. _records = new Dictionary(true);
  26. } if( ! KCSingleton.getClass( api ) ) {
  27. _records[api] = value;
  28. }
  29. }
  30.  
  31. public static function getClass( api:String ):Class {
  32. if( _records == null ){
  33. throw new IllegalOperationError("No records.");
  34. } return _records[api];
  35. }
  36.  
  37. public static function getInstance( api:String ):* {
  38. var instance:Class = KCSingleton.getClass(api);
  39. if( ! instance ){
  40. throw new Error("No class registered for interface \""+api+"\".");
  41. } return instance["getInstance"]();
  42. }
  43.  
  44. public static function purge(...rest):void {
  45. _records = null;
  46. }
  47.  
  48. }
  49.  
  50. }

Report this snippet  

You need to login to post a comment.