10.12.2012 Views

ActionScript 3.0 Design Patterns.pdf - VideoTutorials-bg.com

ActionScript 3.0 Design Patterns.pdf - VideoTutorials-bg.com

ActionScript 3.0 Design Patterns.pdf - VideoTutorials-bg.com

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Figure 3-5. Two instance labels and one instance<br />

You may be wondering how this was possible, because the second instance did not<br />

drop into the part of the constructor that actually created the Singleton instance:<br />

Singleton._instance=new Singleton(new PrivateClass( ));<br />

However, it did not have to because the line,<br />

return Singleton._instance<br />

contains the Singleton instance that had already been created, and simply returned<br />

that instance to the reference name.<br />

While you can guarantee that only one instance of the Singleton class will exist at<br />

any one time, more than a single reference to that instance can exist at the same time<br />

as well. For a shared property used with either increments or decrements, this can be<br />

a very handy way of making sure that only a single source is used by all of the references.<br />

If, for instance, you’re making a game to save miners trapped in a mineshaft,<br />

you need to keep track of the amount of oxygen available for the miners. So if you<br />

create an Oxygen class as a Singleton, all of the miner characters can create a reference<br />

to it, and each one can access a method in the single instance that decrements<br />

the amount of air. Because the amount of air has to be the same for all, the Singleton<br />

be<strong>com</strong>es a handy tool for keeping track of the many references to the single instance<br />

of the class.<br />

When to Use the Singleton Pattern<br />

As noted at the beginning of this chapter, the Singleton design pattern is best<br />

employed when you need one and only one instance of a class in an application. A<br />

couple of examples were discussed, but the use of the Singleton is so ubiquitous in<br />

object-oriented programming that it’s sort of like asking when to use a variable.<br />

Moreover, developers often <strong>com</strong>bine the Singleton design pattern with other patterns.<br />

Where the developer needs a single, global entry point and a single instance,<br />

you’ll often find a Singleton class. Likewise, multiple Singleton classes can be used in<br />

conjunction when you have several different objects where only a single instance of<br />

each object should be instantiated at any one time.<br />

112 | Chapter 3: Singleton Pattern

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!