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.

Chapter 3 CHAPTER 3<br />

Singleton Pattern3<br />

What Is the Singleton Pattern?<br />

The aspects of things that are most important to us are<br />

hidden because of their simplicity and familiarity.<br />

—Ludwig Wittgenstein<br />

Above all be of single aim; have a legitimate and<br />

useful purpose, and devote yourself unreservedly to it.<br />

—James Allen<br />

The Singleton pattern is used all the time, even if you don’t realize you’re using it.<br />

For example, if you have some kind of class that keeps the total number of points in<br />

a game, you want only a single instance of that total. It doesn’t make any sense to<br />

have two totals where the game records only a single total score, like you find in a<br />

single-player pinball game. Likewise, if you create a music application, you want the<br />

application to play only one tune at a time, and so you want only a single instance of<br />

the class that actually plays the music. In fact, most applications have at least some<br />

feature where you want to make sure that there’s only a single instance, and that’s<br />

where you’ll want to use the Singleton design pattern.<br />

Key Features<br />

In a nutshell, the Singleton has two key features:<br />

1. One and only one instance of the class can be instantiated at any one time.<br />

2. The class must have a single, global access point.<br />

You may be thinking, “How hard can that be? As the developer, I can just instantiate<br />

a single instance and use a global variable. Bob’s your uncle, and it’s all done.<br />

Next pattern.”<br />

First of all, as you saw in Chapter 1, OOP and design patterns were devised for teams<br />

of developers, and not just one person working independently. So if you’re involved<br />

101

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

Saved successfully!

Ooh no, something went wrong!