Crea sito

The Singleton pattern



The singleton is very useful in those situations where you want to maintain a unique and global reference in your context for all invokers.



To do this you have to create a class with a static and private (second articles isn't mandatory but a good practise) variable of your preferred type.

After this you'll follow this simple steps inside a public static method that return a reference to your variable:

1) check if the variable x is null

2) if 1) is true create a new instance

3) return the reference to your variable



The simplicity of this pattern is its lack.  For exmple if you think about a context where you need to use a db connection you'll need a synchronized access to avoid concurrency problems.
 Anothere important thing is that you have to avoid singleton when you use a variable few times because maybe you are in a context where you want to avoid waste of resurces.........etc.


That's all and see you next tip :)