Possible Duplicate:
Singleton: How should it be used
hello. i want to know what a singleton is? how to use it? and why do i have to use it. thank you very much. if anybody can give examples with the explanation i would really appreciate it.
Possible Duplicate:
Singleton: How should it be used
hello. i want to know what a singleton is? how to use it? and why do i have to use it. thank you very much. if anybody can give examples with the explanation i would really appreciate it.
If you need only a single instance of an object, then you use singleton. It is one of the many standard design patterns.
Let me clarify with a piece of code -
public class SingleInstance
{
private static final SingleInstance OnlyInstance = new SingleInstance(); // Or Any other value
// Private constructor, so instance cannot be created outside this class
private SingleInstance(){};
public static getSingleInstance()
{
return OnlyInstance;
}
}
Since this class's constructor is private, it cannot be instantiated in your application, thus ensuring that you have exactly one instance of class SingleInstance
.
Use this pattern when you need to ensure only one instance of a particular class is created within your entire application.
To learn more, go here.