Interview Question
Java DevelopersCountry: India
Interview Type: In-Person
For "short" and "long" , IMO they are similar, both per JVM.
If need scale limitation, you can change public to default.
Or register a SecurityManager to limit specific invoking case.
Below is a Singleton example, you can also use Enum or Interface(java1.8+)
package gao.zone.study;
public class MySingleton {
private final static class Holder{
private final static MySingleton INSTANCE = new MySingleton();
}
private MySingleton(){}
public final static MySingleton getInstance() {
return Holder.INSTANCE;
}
public void foo() { }
public <T> T bar() {return null;}
}
For 2. I think a private static class is enough.
From the name it is clear that suppose we want only one instance of a class in JVM then we will use singleton pattern. One such example:
public class HibernateUtils
{
private HibernateUtils()
{
}
private static SessionFactory seesionFactory = null;
private static final SessionFactory makeSessionFactory()
{
try {
if (sessionFactory==null)
seesionFactory = new Configuration().configure().buildSessionFactory();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return seesionFactory;
}
public static SessionFactory getSessionFactory()
{
return makeSessionFactory();
}
}
Short answer: If we want to maintain a single object of a class per JVM .. :)
- Ajeet August 25, 2014Long answer: 1. If we have to maintain some information at single place or dont want to spreed everywhere in application, than we prefer singleton ...like objects for configurations, factories etc.
2. Only single object is enough of a particular functionality (class) like .... starters, initializers etc. etc.