Is the Factory Method Pattern more flexible than Simple Factory?
You are absolutely right: author's assumption has been that you are not going to subclass SimpleFactory
, which is not a fair assumption to make (unless SimpleFactory
is marked final
).
Since SimpleFactory
is not final, you can definitely subclass it, gaining more flexibility than with a factory method, because SimpleFactory
replaces inheritance with composition.
An even better approach would be making SimpleFactory
an interface. Doing so would let you pick composition or inheritance according to your preference, because an interface would not limit you in cases when your Store
class already inherits a class.
public interface SimpleFactory {
Product createProduct();
}
Then you can use either composition
public class FactoryImpl implements SimpleFactory {
public Product createProduct(){
// Return an instance of some subclass of Product
}
}
public class StoreComposition {
SimpleFactory factory = new FactoryImpl();
}
or inheritance/composition combo
public class StoreInheritance implements SimpleFactory {
SimpleFactory factory = this;
public Product createProduct(){
// Return an instance of some subclass of Product
}
}