Singleton – Boon or a Sin

Over last few weeks, I have faced quite a few issues with Cairngorm’s Singleton pattern and I decided to put forward a post that should help in making some decision. While I found a few articles about Singletons, but not even one that talks about how should we use Singletons.

Ask any programmer, and they will instantaneously discourage you with the use of global data (objects). But, many a times when you find a need where you have to have some objects available globally and also need a single point of access example: User’s state, permissions which has to be retrieved globally across the user session. And, it is then when you use the design pattern singleton.

When is a class really a Singleton?

Ask yourself:

  • Will every application use this class exactly the same way?
  • Will every application ever need only one instance of this class?
  • Should the clients be unaware of the application that this class is part of?

If you can answer all the above as a Yes, then you found a singleton – remember your Logger / Logging classes. Thats what you need as a singleton.

Now, let us switch focus to Flex, and how can we make use of a Singleton. As we all know that Flex is all about Events and thats how any two components interact wit each other. Singletons here become very handy, as you can dispatch en event on a Singleton Event Dispatcher and the component who needs to listen to it, can easily be listening on the Singleton. Solves many of our problems. Huh!! does it? I am putting down some code for the Buttons (which I am treating as a component). Try executing this code, and you will find that when you click on any one of the buttons, both the buttons handle the event and show and alert twice.

In my next article, I will explore the issues of Singleton with Cairngorm.

3 thoughts on “Singleton – Boon or a Sin

Initiate your idea here...

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s