I am learning more about the factory design pattern and came across the following example from Microsoft (I recoded it in java). Example here
Short version:
-
An abstract Product class
-
A Concrete Product class that extends Product
-
An abstract Factory class
-
A Concrete Factory class that extends Factory
-
An Assembly class
public class ProductAssembler { public void AssembleProduct(Factory factory) { Product p = factory.getProduct(); //do something } } -
A client
public static void main(String[] args) { Factory factory = new ConcreteFactory(); new ProductAssembler().AssembleProduct(factory); }
Question:
- What is the purpose of creating a factory object in the main method instead of a product object, why don’t they pass a product object to the assembleproduct method and change
that method so it accepts products instead of factories? - Is the assembly class also part of the ‘client’ or not?
Thanks
assembleProduct()inProductAssemblerdoesn’t want to deal with instantiating products. So it wants to delegate this to a Factory so that when newer kinds of products are introduced, the existing factory changes (or a new factory is added) butProductAssemblerdoesn’t need to change. Instead of instantiation,assembleProduct()callsfactory.getProduct().As far as the Factory pattern is concerned,
ProductAssembleris the client. But if you look at it from an application perspective, yourmain()is the client and hence doesn’t deal with Product objects.