'SuperGlobal' OOP variables for actionscript?
I am designing a flash website and I made it object oriented. I have a lot of classes and I am having difficulty in accessing information ( variables ) from other classes.
To do so I usually include the variable at the parameters of my class' functions ( or constructor) OR I create custom event objects that will transport the variables to another class ( that listens for them ). This methods are sluggish.
I know there are local variables ( those who are declared inside a function and are available only to that function ) and global variables ( who are declared inside a class as private or public and are available in that class ). Can I, somehow, create some sort of 'superglobal' variables that are available to the whole flash program?
If not, do you guys know a way to pass along variables in an OOP design?
Th开发者_如何学编程anks! I will try to implement a singleton.
Does NOT have to be anything like singleton. The solution is quite simple:
package sg {
public class SuperGlobal {
public static var vars:Array = new Array();
}
}
Wherever you are in your code, you can access the vars array with this:
sg.SuperGlobal.vars["test"] = "Hello World!";
// somewhere else:
trace(sg.SuperGlobal.vars["test"]); // Hello World!
Usually one does this with a singleton class that holds some variables that can be used everywhere. Make one class for instance called "Environment", "Settings" or "Program", that holds some static variables, each class can then access these through Settings.soundIsMuted, for instance.
Singleton class:
package {
public class SingletonDemo {
private static var instance:SingletonDemo;
private static var allowInstantiation:Boolean;
public static function getInstance():SingletonDemo {
if (instance == null) {
allowInstantiation = true;
instance = new SingletonDemo();
allowInstantiation = false;
}
return instance;
}
public function SingletonDemo():void {
if (!allowInstantiation) {
throw new Error("Error: Instantiation failed: Use SingletonDemo.getInstance() instead of new.");
}
}
}
}
I think I get it now. Thanks!
精彩评论