views:

101

answers:

2

Hey,

So.. I can't understand why should I even use the Singleton pattern in ActionScript 3. Can anyone explain me this? Maybe I just don't understand the purpose of it. I mean how it differs from other patterns? How it works? I checked the PureMVC source and it's full of Singletons. Why are they using them in the View, Module, Controller?

+1  A: 

The singleton pattern restricts the instantiation of an object to only one instance. Sometimes in systems this pattern is used so an object that controls parts of the system can't be just created at-will. If you have some object that manages settings, for example, you would want something that changes settings to only modify that one object, and not create a new one.

Ryan Hayes
Actually, I don't think saving resources was ever the reasoning behind singletons. Rather, a singleton is designed to only ever be instanced once and globally accessible. A common example for the use of a singleton include having only one reference to a printer. However, this pattern is considered by many to be an anti pattern.
macke
Yea, for some reason I was thinking flyweight (extension of singleton...er...multiton) when I wrote my original answer, which I thought I deleted before writing this one. Do you still see the original one?
Ryan Hayes
So, so far I understand that once it's initiated it can't be initiated again and can be accessed globally. Okay, what it does is clear, but can anyone give some clear examples of why/what cases I should use it in programming?
Richards
Odd, I saw the other answer when I wrote my comment, but not any more.
macke
+3  A: 

I have next to no practical experience with PureMVC so I can't argue for or against their use of Singletons. Hence, I'll try to keep my answer more generic.

A singleton is a type of object that can only be instantiated once and is globally accessible.

Typically, this kind of pattern is used in order to have easy access to services of some kind, perhaps a service facade used to retrieve data from a server or an application model that holds information about settings or such.

The singleton pattern is by many considered to be an anti-pattern for a number of reasons, a few of which are mentioned below:

  1. They carry state, making certain tasks such as unit testing virtually impossible.
  2. They inherently violate the Single Responsibility Principle.
  3. They promote tight coupling between classes due to them being globally accessible.

I won't list all of the reasons why a singleton may be an anti pattern, there are plenty of resources on the subject.

macke