Chapter 3. Singleton Pattern

The aspects of things that are most important to us are hidden because of their simplicity and familiarity.

Ludwig Wittgenstein

Above all be of single aim; have a legitimate and useful purpose, and devote yourself unreservedly to it.

James Allen

What is the Singleton Pattern?

The Singleton pattern is used all the time, even if you don’t realize you’re using it. For example, if you have some kind of class that keeps the total number of points in a game, you want only a single instance of that total. It doesn’t make any sense to have two totals where the game records only a single total score, like you find in a single-player pinball game. Likewise, if you create a music application, you want the application to play only one tune at a time, and so you want only a single instance of the class that actually plays the music. In fact, most applications have at least some feature where you want to make sure that there’s only a single instance, and that’s where you’ll want to use the Singleton design pattern.

Key Features

In a nutshell, the Singleton has two key features:

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

  2. The class must have a single, global access point.

You may be thinking, “How hard can that be? As the developer, I can just instantiate a single instance and use a global variable. Bob’s your uncle, and it’s all done. Next pattern.”

First of all, as you saw in Chapter 1, OOP and design patterns were devised for teams of developers, ...

Get ActionScript 3.0 Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.