Static Main Class - AS3

Is there a way to make the main class - one that is based on the main .fla - static? therefore, we could use it as in java, having the ability to refer to it from other classes, because I have to pass an instance of myself as a parameter to the class, otherwise I will lose the link. I tried adding a static prefix, but it seems 3 does not allow it.

+6
source share
2 answers

In AS3 there is no concept of a static class.

You can use the singleton template to open a unique instance of your main class:

public class Main extends Sprite { public static var instance:Main; public function Main() { instance = this; } 

... or just mark other properties / methods as static , although it becomes more difficult to manage with this.

I need to mention that using static sometimes leads to poor code development (instead, you can pass an instance of Main to classes that need it through your constructor, for example)

+9
source

This will not be a popular answer, I know ... Using static properties to expose instances is a really bad idea. The Singleton anti-pattern is very popular, but should not be, it leads to incorrect practice and unnecessarily binds classes to each other.

You need to ask yourself if you really need to refer to the main class in other classes? AS3 has an event system that can provide you with all the clutch you need. If the display object should interact with an instance of the main class, this can be done by sending events through the display list.

The problem of dependency management is best handled by the dependency injection infrastructure (many of which have some centralized messaging system that far surpasses the list of events behind the list). If you feel that any of the popular ones (PureMVC, RobotLegs, etc.) is redundant, you can easily create (simple and limited) yourself.

There are many tools and templates that never have to rely on singletones or static instance applicators because they make your life miserable and your code fragile, inflexible, unstable, unreliable and buggy.

+3
source

All Articles