来自各地的AS3访问类实例

时间:2011-12-29 15:04:08

标签: actionscript-3 class global

对于我当前的项目我开始使用AS3并且我编写了一个ClipManager类,我可以在初始化过程中定义像“mainView”这样的MC,如下所示:

clipManager:ClipManager = new ClipManager(mainView);

使用我的clipManager,我现在可以轻松地将内容加载到mainView等中。问题是我希望整个事物中的每个按钮都能访问此实例的类方法来更改mainView。我可以在Flash中使用类似全局的Class实例,还是有更聪明的方法来实现我想要做的事情?

1 个答案:

答案 0 :(得分:3)

您可以将ClipManager类添加为某个静态 - 即上帝对象 - (可能是您的主类)并通过它访问它,或者您可以使用Singleton模式。

在as3中实现它的常用方法:

public class Singleton
{
    private static m_instance:Singleton = null; // the only instance of this class
    private static m_creating:Boolean   = false;// are we creating the singleton?

    /**
     * Returns the only Singleton instance
     */
    public static function get instance():Singleton
    {
        if( Singleton.m_instance == null )
        {
            Singleton.m_creating    = true;
            Singleton.m_instance    = new Singleton;
            Singleton.m_creating    = false;
        }
        return Singleton.m_instance;
    }

    /**
     * Creates a new Singleton. Don't call this directly - use the 'instance' property
     */
    public function Singleton()
    {
        if( !Singleton.m_creating )
            throw new Error( "The Singleton class can't be created directly - use the static 'instance' property instead" );
    }
}

现在,要访问您的课程,请致电Singleton.instance。这个类只有一个实例。

至于反模式等,这是另一篇文章:)

相关问题