1

我正在尝试来自fluffycat的构建器示例

SodaImpSingleton sodaImpSingleton = new SodaImpSingleton(new CherrySodaImp());
System.out.println("testing medium soda on the cherry platform");
MediumSoda mediumSoda = new MediumSoda();
mediumSoda.pourSoda();

这里 sodaImSingleton 和 mediumSuda 之间没有关系,仍然当 mediumSoda.pourSoda() 被调用时,它会打印 CherrySodaImp.pourSodaImp() 如何/为什么会发生这种情况?

4

2 回答 2

1

There is a relationship. The SodaImpSingleton is instantiated with a CherrySodaImp. Next, MediumSoda extends Soda and in its constructor it is calling the method setSodaImp(), which is implemented as SodaImpSingleton.getTheSodaImp(); in the abstract Soda class, a static method that returns the CherrySodaImp instance created on the first line.

于 2013-05-09T14:45:12.923 回答
1

MediumSode.pourSoda()Soda.this.getSodaImp()返回Soda.this.sodaImpMediumSoda()构造函数通过Soda.this.setSodaImp()to设置的调用static SodaImpSingleton.getTheSodaImp()。的返回值SodaImpSingleton.getTheSodaImp()是通过调用全局设置的new SodaImpSingleton(new CherrySodaImp())

这个例子太复杂了,我称之为无效。

适当的最小单例实现将是:

public class Singleton {  
    private static Singleton instance;

    private Singleton () {
    }

    public static Singleton instance() {
        if(instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

虽然它不是安全的。

于 2013-05-09T14:45:41.630 回答