I am attempting to learn the Singleton design pattern and I came across the following example. However, it seems to let me create two instances of the class. I thought the point of a Singleton was to only allow a single instance of a class to be created at any given time. Can anyone explain what I'm missing here? How can I verify that only one object is being created at any given time?
public class ChocolateBoiler {
private boolean empty;
private boolean boiled;
private static ChocolateBoiler uniqueInstance;
private ChocolateBoiler(){
empty = true;
boiled = false;
}
public static synchronized ChocolateBoiler getInstance(){
if(uniqueInstance == null){
uniqueInstance = new ChocolateBoiler();
}
return uniqueInstance;
}
public void fill(){
if(isEmpty()){
System.out.println("filling");
empty = false;
boiled = false;
}
System.out.println("already full");
}
public boolean isEmpty(){
System.out.println("empty");
return empty;
}
public boolean isBoiled(){
System.out.println("boiled");
return boiled;
}
public void drain() {
if (!isEmpty() && isBoiled()) {
System.out.println("draining");
empty = true;
}
System.out.println("already empty");
}
public void boil(){
if(!isEmpty() && isBoiled() ){
System.out.println("boiled");
boiled = true;
}
System.out.println("either empty or not boiled?");
}
public static void main(String[] args) {
ChocolateBoiler boiler1 = new ChocolateBoiler();
boiler1.fill();
boiler1.boil();
boiler1.boil();
boiler1.drain();
boiler1.drain();
boiler1.isEmpty();
System.out.println("\nboiler 2");
ChocolateBoiler boiler2 = new ChocolateBoiler();
boiler2.fill();
System.out.println("\nboiler 1");
boiler1.isBoiled();
}
}
Aucun commentaire:
Enregistrer un commentaire