Singleton class is use to create one and only one instance of the class. It is use to create singleton database connection. To ensure that no one extends the class and expose the constructor, make the class final.
Login to rate this answer.
In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. The term comes from the mathematical concept of a singleton.
There is criticism of the use of the singleton pattern, as some consider it an anti-pattern, judging that it is overused, introduces unnecessary restrictions in situations where a sole instance of a class is not actually required, and introduces global state into an application.---As per Wiki
Normally we do it
Code
public class SingletonDemo {
private static volatile SingletonDemo instance = null
private SingletonDemo() { }
public static SingletonDemo getInstance() {
if (instance == null) {
synchronized (SingletonDemo .class){
if (instance == null) {
instance = new SingletonDemo ()
}
}
}
return instance
}
}
in this manner but
Code
class SingletonClass
{
private static int count=0
SingletonClass() throws Exception
{
if(count==0)
{
System.out.println("Object Created.")
count++
}
else throw new Exception("Singleton Class cannot have more than one Object.")
}
public static void main(String args[])
{
try{
SingletonClass s1=new SingletonClass()
SingletonClass s2=new SingletonClass()
SingletonClass s3=new SingletonClass()
}catch(Exception e)
{
System.out.println("Exception: "+e.getMessage())
}
}
}
in this manner by using the if condition you can create n-ton class
Login to rate this answer.
MN Prasad
Answered On : Dec 29th, 2012
Singleton class is used for only one instance is created for entire application. One instance and multiple threads.
Code
class Singleton
{
private static int singleton;
private Singleton()
public static Singleton getUniqueInstanceID()
{
if (singleton== null)
{
singleton = new Singleton();
}
}
}
Login to rate this answer.