最好的方法是创建一个叫做“singleton”的东西。很简单,单例是一个静态类,没有静态类的所有讨厌的缺点。它使单个实例(或单个副本)在全局范围内可用,然后其行为与常规实例完全相同(因为它是)。
通过使用静态变量和函数可以实现单例。静态变量/函数是 类 的一部分,而不是实例。因此,每个变量只能有一个(只有一个类)并且它们都是全局可访问的。静态函数和属性的一个很好的例子是内置的Math 类。你得到 Pi 的值是这样的:
Math.PI
不是这样的:
var math:Math = new Math();
math.PI
如您所见,它是具有方法的类。我们可以通过提供一个静态的getInstance() 函数来使用它来创建一个单例,该函数将是全局可访问的,并且总是返回相同的对象。这是单例的示例实现:
package {
public class SingletonSample {
// The singleton instance
private static sharedSingleton:SingletonSample = null;
// The constructor. AS3 doesn't allow for private constructors
// so we have to protect it manually
public function SingletonSample() {
if (sharedSingleton != null)
throw new Error ("SingletonSample cannot be created with the new keyword. Use getInstance() instead.");
}
// The method that will get the actual instance
public function getInstance():SingletonSample {
if (sharedSingleton == null)
sharedSingleton = new SharedSingleton();
return sharedSingleton;
}
}
}
除了示例中定义的那些方法和变量之外,该类的其余部分都可以正常编程。然后,当您想在代码中使用该类时,不要这样做:
var instance:SingletonSample = new SingletonSample();
instance.doAThing(instance.aProperty);
这样做:
var instance:SingletonSample = SingletonSample.getInstance();
instance.doAThing(instance.aProperty);
实际上,当您只是快速调用方法时,根本不需要创建局部变量。只需执行以下操作:
SingletonSample.getInstance.aQuickFunction();
只要 SingletonSample 类已经被导入,这一切都是全局可用的。这种设计模式是一个很棒的“管理器”类,因此它可能会满足您的需求。但请记住,单例通常不适合作为可操作对象。如果您愿意,可以将它们用作提供对其他事物的引用的经理,一种“中间人”类。但是,如果使用得当,它们可以成为程序员武器库中强大而方便的工具。