Acha Bhoot Acha Bhoot -3 years ago 85
Java Question

Confusion in Builder plus Singleton pattern in example from fluffycat

I was tryingout builder examples from fluffycat

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


here there is no relation between sodaImSingleton and mediumSuda,
still when mediumSoda.pourSoda() is called it prints
CherrySodaImp.pourSodaImp() how/why is this happening?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download