Art*_*mix 6 singleton actionscript-3 static-classes
我知道,好朋友不是"对抗"问题的粉丝,但是......甚至还有一点点重述,对比部分仍然存在,所以,为什么要隐藏它.
基本上,我想,当知道我为什么要使用一个单身或静态类,有什么可以提供单一个静态类倾斜,反之亦然.
很长一段时间我都使用了两者,我无法看到为什么我不应该使用其中一个.
谢谢.
两者基本上都是全局变量,有警告.静态类可以防止继承,而Singletons很难看,并且通过属性查找增加了开销.两者都使自动化测试困难.
AS3支持全局变量,为什么不使用它们呢?
静态的:
package com.example
{
public class Config
{
public static var VERSION:uint = 1;
}
}
Run Code Online (Sandbox Code Playgroud)
单身:
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
}
}
}
Run Code Online (Sandbox Code Playgroud)
全局变量:
package com.example
{
public var config:Config = new Config();
}
class Config
{
public var version:uint = 1;
}
Run Code Online (Sandbox Code Playgroud)
现在,假设您只想在生产应用程序中使用该类的单个实例,则需要多个实例来编写测试.您可以创建公共类Config
,并使用com.example.config = new Config()
重置.引用您的全局变量的所有位置现在都在使用新实例,您甚至可以执行像继承这样的花哨的事情.
例如:
if(inDebugMode)
{
com.example.config = new DebugConfig();
}
{
com.example.config = new Config();
}
Run Code Online (Sandbox Code Playgroud)