Search code examples
javaoopdesign-patternsfactory-pattern

Factory Pattern and dependencies


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:

  1. with this design pattern we have still a dependency to class Product (myProd) (1)
  2. moreover.. we have a dependency with Concrete-Factories (client needs to instantiate a specific wanted concrete factory and client must know witch one) (2)

Tank you for any clarification.


Solution

    1. We do have a dependency on Product, but the point is to eliminate the dependency on ConcreteProduct.

    2. 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.