AS3: Static class versus Singleton

徘徊边缘 提交于 2019-12-04 05:46:48

Both are basically global variables with caveats. Static classes prevent inheritance, and Singletons are ugly and add overhead with a property lookup. Both make automated testing difficult.

AS3 supports global variables, so why not use those?

Static:

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

Singletons:

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 even though you only want a single instance of the class in your production app, you need multiple instances to write tests. You can make a public class Config, and use com.example.config = new Config() to reset. All the places that reference your global variable are now using the new instance, and you can even do fancy things like inheritence.

For example:

if(inDebugMode)
{
    com.example.config = new DebugConfig();
}
{
    com.example.config = new Config();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!