Is there a way to make the main class - the one based on the main .fla - static? so we could use it as in java, being able to reference it from other classes, because I have to pass the instance of the main itself as a parameter to a class, otherwise I loose reference. I tried to add static prefix but seems as3 doesn't allow it.
问题:
回答1:
There is not concept of static class in AS3.
You can use the singleton pattern to expose the unique instance of your main class :
public class Main extends Sprite {
public static var instance:Main;
public function Main() {
instance = this;
}
...or just mark expose other properties/methods as static
, although it becomes harder to manage.
I need to mention though that using static
sometimes leads to bad code design (instead, you can pass the instance of Main
to classes that need it through their constructor for instance)
回答2:
This won't be the popular answer, I know... Using static properties to expose instances is a really bad idea. The Singleton anti-pattern is very popular, but shouldn't be, it leads to bad practices and unnecessarily ties classes to each other.
You need to ask yourself whether you really need to reference the main class in other classes? AS3 has an event system which can provide you with all the loose coupling you need. If a display object needs to communicate with the main class instance this can be accomplished by sending events through the display list.
The problem of dependency management is best handled by a dependency injection framework (many of which have some centralized messaging system, which beats the events-over-the-displaylist by far). If you feel any of the popular ones (PureMVC, RobotLegs, etc.) is overkill you can easily create (a simple and limited) one yourself.
There's plenty of tools and patterns to never ever ever having to rely on Singletons or on static instance accessors, because they make your life miserable and your code brittle, inflexible, untestable, unreliable and buggy.