-1

When I feel the need of having a factory class in my projects, I'm tempted to use this approach:

public class ProductFactory {

     public Product makeProduct(Type t){
          switch (t)  {
             case A: return new ProductA(); break; 
             case B: return new ProductB(); break;
             default: throw new UnsupportedTypeException();
          }    
          return null;   
     }
}

Where the logic for the product selection is encapsulated within the factory object.

With the abstract factory pattern, instead, from what I have learned, the approach is to abstract the factory as well, and instantiate it according to the product selection logic.

 public class ProductFactoryFactory {

     public ProductFactory getProductFactory(Type t){
          switch (t)  {
             case A: return new ProductFactoryA(); break; 
             case B: return new ProductFactoryB(); break;
             default: throw new UnsupportedTypeException();
          }  
          return null;   
     }    

}

In both cases whenever a new product is added, a switch needs to change somewhere in order to include the newly created product.

My question is if I'm missing something with my approach and what would be the advantages of using the abstract factory instead.

DanTheMan
  • 191
  • 4
  • 11
  • This won't compile, you have a `return` and a `break`. What you're missing is DI! – Boris the Spider Dec 06 '14 at 15:26
  • This question appears to be off-topic because it is not a specific question but a general question about design patterns. As such it belongs on Programmers SE. – Boris the Spider Dec 06 '14 at 15:29
  • @BoristheSpider thank you, I have corrected the code. I have omitted dependencies for the sake of simplicity. Could you explain better how does Dependency Injection relate? – DanTheMan Dec 06 '14 at 15:41
  • 1
    Skipping imports is perfect! Unless they are relevant, which here they are not. You still have a `return new ...` followed by a `break` - this is an unreachable statement. DI would allow you to decide which impl of a `class` to inject at runtime - both these patterns solve the same issue. – Boris the Spider Dec 06 '14 at 15:42

1 Answers1

0

In Factory pattern, you already decided the ProductFactory implementation you integrated

In Abstract Factory pattern, you can decide the ProductFactory to be integrated during runtime. In contrast, the ProductFactory and its caller are not coupled at compile time

Patrick Chan
  • 1,019
  • 10
  • 14