Expedia Interview Question
Software Engineer / DevelopersCountry: United States
public class Singleton {
private static Singleton singleton =null;
private Singleton(){
}
public static Singleton getInstance(){
if(singleton = =null){
singleton = new Singleton();
}
return singleton;
}
}
hi Hari you are right but i right for general purpose but we also prevent from cloning so will use clone() method
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException("Cloning of this class is not allowed");
}
Cloning has nothing to do with synchronization. If two threads read from a field at the same time and make two different alterations to it and write it back, you are going to lose one of the alterations.
I know Synchronization and cloning both are different things but in case of Cloning than we will have make cloning restriction.
@ maverick
its not about loosing one alterations. if two threads call gentInstance at roughly the same time and if thread1 gets preempted after evaluating if cond to true and thread2 completes getInstance call and it creates one instance and then thread1 wakes up and goes on to create one more instance
creating only one object for a particular class.program to create a single ton design pattern
import java.io.*;
class SingleTon
{
static SingleTon s1=new SingleTon();
private SingleTon(){
}
static SingleTon getObject()
{
return s1;
}
public static void main(String... args) throws Exception
{
SingleTon st=SingleTon.getObject();
SingleTon st1=SingleTon.getObject();
if(st.equals(st1))
System.out.println("equal");
}
}
The Singleton is a object-oriented designed pattern where you ensure there is one and only one instance of a class being used. An example where you want to use this pattern is when designing cash register. A cash register can be decompose to smaller individual items including a sales tax calculator. There should be only one instance of the tax calculator used.
- pete May 30, 2012