Creating a Singleton instance creating multiple objects

I am trying to learn the Singleton design pattern and I came across the following example. However, it seems that I can create multiple instances of the class.

I thought that a singleton point should only allow one instance of a class to be created at any given time. Can someone explain what I'm missing here? How can I verify that only one object is 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();
    }
}
+4
source share
1 answer

ChocolateBoiler , , ( main).

Singleton , ChocolateBoiler ( getInstance), .

+8

Source: https://habr.com/ru/post/1615195/


All Articles