I try to understand the SOLID principles and therefore implemented some java snippets. My concern is the OCP at the moment. Having following samples,
public abstract class Bakery
{
public abstract Bakegood bake();
}
/******************************************/
public class BreadBakery extends Bakery {
@Override
public Bakegood bake() {
return new Bread();
}
}
/******************************************/
public class CakeBakery extends Bakery {
@Override
public Bakegood bake() {
return new Cake();
}
}
/******************************************/
how can I create the right bakery. Assume a customer comes to the bakery and says: "I'd have two cakes, please!", how can I then instantiate the CakeBakery. Of course I can create an abstract factory like:
public static Bakery createBakery(final String orderedBakegood)
{
switch(bakegood)
{
case "Cake": return new CakeBakery();
case "Bread": return new BreadBakery();
default: throw new InvalidBakeryException();
}
}
But I don't want to use switch or if statements. Is there any other possibility or am I completely wrong with the understanding?