1

ふわふわキャットのビルダーの例を試していました

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

MediumSode.pourSoda() calls Soda.this.getSodaImp() that returns Soda.this.sodaImp that is set by MediumSoda() constuctor via Soda.this.setSodaImp() to static SodaImpSingleton.getTheSodaImp(). The value returned by SodaImpSingleton.getTheSodaImp() is set globally by calling new SodaImpSingleton(new CherrySodaImp()).

This example is so convoluted that I'd call it invalid.

Proper minimal singleton implementation would be:

public class Singleton {  
    private static Singleton instance;

    private Singleton () {
    }

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

though it is not thead-safe.

于 2013-05-09T14:45:41.630 に答える