A singleton doesn't need 1.5 GW |
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:
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.
Post a Comment