Friday, 19 November 2010

The power of a "Singleton"

«Please, excuse me if I didn't update my blog in these days. I was so busy in some activities, both at work and for my movie. Yesterday, with Fabio, I looked for a good place to realize some scenes. We were lucky!»
A singleton doesn't need 1.5 GW
In this post I'll talk about singletons, last design-pattern I found. If they're necessary in Cocoa, they're also usefull in other programming contexts. What's a singleton, exactly? On wikipedia it's defined as «the instantiation of a class to one object» and well, it's right.By a programming point of view it looks like (in Java):

class MySingleton{
    private static MySingleton shared_singleton=null;
    private int counter;

/** * Private constructor */
private MySingleton(){ counter=0; }
/* * Increment counter */
private void Increment(){ counter++; }
/* * get the singleton */
private static MySingleton getSharedSingleton(){ if (shared_singleton==null) shared_singleton=new MySingleton(); return shared_singleton; } }

You see, when you're using a singleton, you have just one instance of this object (here it's called shared_singleton). You can get a reference to this object with the getSharedSingleton static method.
In Cocoa touch, singletons are the most confortable way to have a shared resource; global variables, (very used in C) aren't good as a singleton. In Java you can insert them easily in a multithreaded context, just adding the synchronized keyword. Singletons are very good to share read-only data and they can be used in every object-oriented programming language.

Singletons could be dangerous, because (if they're not well designed) they could know too much about other objects, can grow in functions if they're not well designed a can give throubles in a multi-threaded environment. A detailed description about dangers of singletons abuse is Use your singletons wisely by J. B. Rainsberger, employed at IBM. It's an interesting lecture if you are a programmer. Another good lecture is Singleton Pattern description, where there's also some example of "Singleton Abuse".

1 comment:

Anonymous said...

Even symfony uses singleton pattern for some stuff, it's really useful when you have to share informations and functionalities in your applications; it's also very dangerous if it's modified / accessible from each part of the application.