public class MySingleton
{
   private static var _instance:MySingleton;
   public static function get instance():MySingleton
   {
       if (!_instance) _instance = new MySingleton();
       return _instance;
   }

   public function MySingleton()
   {
       if (_instance) throw new Error("MySingleton is a singleton but has
been constructed twice!");
   }
}

That works for me. There's also a technique where you use an internal class
(visible only within the AS source file) as a parameter to the constructor,
thus causing the compiler to complain if anyone calls the constructor from
outside that source file, but I find that throwing the error is enough.

Another option is to go with a Monostate, which doesn't require any trickery
in ActionScript. In a Monostate, you can create as many instances of the
class as you want but they're all basically just facades onto a single
instance (usually implemented as just having private static members). In
some cases I like the Monostate better because, depending on the
application, its easier to switch to not being an "oop global" if need be.

Troy.



On 3/27/07, Petro Bochan <[EMAIL PROTECTED]> wrote:

   Hi,



As a side note, you might try to place your .AS file in the root directory
(along with your main .MXML application file) and define all the necessary
methods there. The methods should be all public though but the advantage is
that you are not even required to define a package. Methods shouldn't be
even static.



Cheers,

Petro


  ------------------------------

*From:* [email protected] [mailto:[EMAIL PROTECTED] *On
Behalf Of *Andre Rodrigues Pena
*Sent:* Monday, March 26, 2007 11:50 PM
*To:* [email protected]
*Subject:* [flexcoders] Global access in AS3



Hi all,

My problem is: I need some data classes to be global so that I can
access them without to have to establish unnecessary references.

I tried to create a Singleton class the way we're used to do in Java,
and I got 2 problems:

1) It's not possible to define a private constructor
2) The instance created in the getInstance() method is not keeping the
data, I don't know why

What do I do to have globally accessible structures in AS3?

--
André Rodrigues Pena

LOCUS
www.locus.com.br

Blog
www.techbreak.org

Reply via email to