Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton instantiation creating multiple objects

I am attempting to learn the Singleton design pattern and I came across the following example. However, it seems that I am able to create multiple 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();
    }
}
like image 245
Michael Queue Avatar asked Feb 08 '23 14:02

Michael Queue


1 Answers

Inside the ChocolateBoiler class you have access to the private constructor, so you can create as many instances as you like (as you demonstrate in your main method).

The point of the Singleton pattern is that outside your class, only one instance of ChocolateBoiler can be obtained (via the getInstance method), since the private constructor can't be accessed from the outside.

like image 138
Eran Avatar answered Feb 19 '23 11:02

Eran