The factory method is used to avoid violation of Open-closed principle. Instead of creating an object by inheritage:
Product myProd = new ConcreteProduct1; // concreteProduct extends abstract product
myProd.doSomething();
we use a factory "interface" with relatives concrete factories (classes that implement factory and overrride its methods):
Factory myFact = new ConcreteFact1; // (2)
Product myProd = myFact.createProd(); // (1)
myProd.doSomething(); // (1)
I read much about factory method; I understood that, using factory method, it's possible to exclude vilations of the open-closed principle. But I still don't understand:
Tank you for any clarification.
We do have a dependency on Product
, but the point is to eliminate the dependency on ConcreteProduct
.
No, we don't have a dependency on ConcreteFactory
because we get passed the factory as a parameter.
class MassProduction {
ProductFactory factory;
public MyClass(ProductFactory fact) {
factory = fac;
}
public List<Product> produce(int amount) {
ArrayList<Product> result = new ArrayList<>(amount);
for (int i = 0; i < amount; i++) {
result.add(factory.createProduct());
}
return result;
}
}
At no point do we have a dependency on either ConcreteProduct
or ConcreteFactory
.