Singleton Versus Static Members


After examining the structure of a Singleton class, you might ask the question, "Why not just make all the properties and methods of the class static? Why do we need to have an instance at all?" There are a few reasons why a Singleton is the better approach.

The first reason is inheritance. In ActionScript 3.0, you cannot inherit static properties or methods. Therefore, if all your class's functionality is in static methods, you cannot subclass it.

The second reason to use a Singleton pattern is so that you can refactor the class to allow more than one instance. A lesser-known design pattern called the Multiton is similar to the Singleton but allows for a managed number of instances. If you write your original class as a Singleton, you can refactor it to be a Multiton easily. For example, let's say version 1.0 of your application had a connection manager that managed a single connection to the server; but for version 2.0, it has been determined that you need to manage a pool of 10 connections to the server. This is where a Multiton could be used.

The third reason is that it can be a waste of resources to have all this logic initialized right away. Singletons use the concept of "lazy" instantiation, because the object is created only when the first call to getInstance() is made. Classes that use all static members do what is called "eager" instantiation. This is usually a waste of resources and can slow down the startup of your application.

Lastly, objects are just easier to manage. By using static methods instead of a single object your code is not created at a specific point in your application. This can cause some strange initialization issues that are difficult to debug. This is especially true if your Singleton class has a dependency on other objects in the application that might not be initialized. For this reason, consider using static members only if your class is 100% self-contained, with no dependencies on outside objects. Even then, your class is locked into this "self-contained" mode and isn't scalable anymore.




Advanced ActionScript 3 with Design Patterns
Advanced ActionScript 3 with Design Patterns
ISBN: 0321426568
EAN: 2147483647
Year: 2004
Pages: 132

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net