单例实例化创建多个对象

时间:2015-11-10 08:46:01

标签: java oop design-patterns singleton

我正在尝试学习Singleton设计模式,我遇到了以下示例。但是,似乎我能够创建该类的多个实例。

我认为Singleton的观点是只允许在任何给定时间创建一个类的单个实例。任何人都可以解释我在这里缺少的东西吗?如何验证在任何给定时间只创建一个对象?

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();
    }
}

1 个答案:

答案 0 :(得分:8)

ChocolateBoiler类中,您可以访问私有构造函数,因此您可以根据需要创建任意数量的实例(正如您在main方法中演示的那样)。

Singleton模式的要点是在类之外,只能获得ChocolateBoiler的一个实例(通过getInstance方法),因为无法从外部访问私有构造函数