Tutorials, extensions, and source files for ActionScript, Flash, and other Adobe products.

 

senocular.com ActionScript Library

Enforce.as

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.senocular.utils {
	
	import flash.utils.getQualifiedClassName;
	import flash.utils.Dictionary;
	
	/**
	 * Enforces a class to act as an abstract or (mostly) singleton class
	 * 
	 * Usage:
	 * function MyClass() {
	 * 	// abstract enforcement allows no constructor calls
	 * 	new Enforce(this, MyClass).isAbstract();
	 * }
	 * // or
	 * function MyClass() {
	 * 	// singleton enforcement allows one constructor call
	 * 	new Enforce(this, MyClass).isSingleton();
	 * }
	 */
	public class Enforce {
		
		protected static var singletons:Dictionary = new Dictionary();
		
		protected var instance:Object;	// instance to check
		protected var compareClass:Class;	// allows comparison protecting inheritance
		
		public function Enforce(instance:Object, compareClass:Class) {
			this.instance = instance;
			this.compareClass = compareClass;
		}
		
		/**
		 * throws error is constructor for instance is called
		 */
		public function isAbstract(error:Error = null):void {
			if (instance.constructor === compareClass) {
				if (error == null) {
					error = new ArgumentError("Cannot instantiate abstract class " + getQualifiedClassName(instance) + ".");
				}
				throw error;
			}
		}
		
		
		/**
		 * throws error is constructor for instance is called more than once
		 */
		public function isSingleton(error:Error = null):void {
			if (singletons[compareClass]) {
				if (instance.constructor === compareClass) {
					if (error == null) {
						error = ArgumentError("Cannot instantiate singleton class " + getQualifiedClassName(instance) + ". Use getInstance() instead.");
					}
					throw error;
				}
			}else{
				singletons[compareClass] = true;
			}
		}
	}
}