AS3:静态类与单身 [英] AS3: Static class versus Singleton

查看:272
本文介绍了AS3:静态类与单身的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,这样的好朋友是不是迷对的问题,但......甚至改写了丝毫不差了一下,对部分依然存在,那么,为什么要隐藏它。

I know SO pals are not fans of "versus" questions but... even rephrasing the tittle a bit, the versus part is still there, so, why hide it.

基本上,我想知道,我为什么要使用一个单身或静态类,有什么可以提供一个单一个静态类倾斜,反之亦然。

Basically, I'd like to know when and why should I use a singleton or a static class, what can offer a singleton that a static class cant, and vice versa.

在很长一段时间,我用这两个,我不能明白了一个道理,为什么我不应该用一个比其他。

For a long time I used both, and I cant see a reason why I shouldn't use one over the other.

感谢。

推荐答案

两者都具有基本的注意事项全局变量。静态类prevent继承和单身是丑陋和属性查找增加开销。既能使自动化测试难度。

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支持全局变量,那么为什么不使用那些?

AS3 supports global variables, so why not use those?

静态:

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

单身:

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
        }
    }
}

全局变量:

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

现在,让我们说,即使你只想要类生产应用程序的一个实例,则需要多个实例编写测试。你可以做一个公共类配置,并使用 com.example.config =新配置()重置。所有引用现在使用新的实例全局变量,你甚至可以做花哨的东西如继承的地方。

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.

例如:

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

这篇关于AS3:静态类与单身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆