AS3: Static Class vs. Singleton

I know that SO-buddies are not fans of the โ€œconsโ€ questions, but ... they even rephrase a bit, compared to the part there are still, therefore, why hide it.

Basically, I would like to know when and why I should use a singleton or static class, what can a singleton offer that a static class does not fit, and vice versa.

For a long time I used both options, and I cannot understand the reason why I should not use one over the other.

Thanks.

+6
source share
1 answer

Both are mostly global variables with reservations. Static classes prevent inheritance, and singletones are ugly and add overhead with property searches. Both make automated testing difficult.

AS3 supports global variables, so why not use them?

Static

package com.example { public class Config { public static var VERSION:uint = 1; } } 

Loners:

 package com.example { public class Config { public static var instance:Config = new Config(); public var version:uint = 1; public function Config() { //Boiler plate preventing multiple instances } } } 

Global variable:

 package com.example { public var config:Config = new Config(); } class Config { public var version:uint = 1; } 

Now, let's say, although you only need one instance of a class in your working application, you need several instances to write tests. You can create an open Config class and use com.example.config = new Config() to reset. All places that reference your global variable now use the new instance, and you can even do fantasies like inheritance.

For example:

 if(inDebugMode) { com.example.config = new DebugConfig(); } { com.example.config = new Config(); } 
+7
source

All Articles