Monday, October 01, 2007

Factory and Abstract Factory:

In factory we have to provide a FactoryClass that can construct different products. The product type that needs to be constructed is usually specified in the argument for the factory method, or a different method for each product can be specified pushing the responsibility onto the client modules to invoke the right product.

Suppose we have three products A,B and C. And lets have a factory class F. F can have either createProduct(argument) or createA(); createB(); createC() implementations.

One disadvantage with this approach is that it does not allow for extensibility. Every time we need to add a new product code we end up changing the code in Factory class. Lets say if there is new product D, then we’ll have to add a new method createD() or change the code for createProduct(). But, if we can have a class called product (assuming all A,B,C and D are of same type) and if we can classify A,B,C and D as Product, then by having a separate factory class for A, B or C will allow in future to just add any new factory class for a new product with out touching the existing code. So, it will be A, B, C, D, E…..

Allowing clients to specify their concrete factory class, allows to add new client code that uses new ProductFactory with minimal effort. For this to work we generally declare earlier ProductFactory as an Abstract class, as it really does not create any classes, and all Afactory, Bfactory…. As concrete factories.
Each concrete factory creates its product type and abstract factory refers to abstract product. I guess there is no need to say that this is AbstractFactory.

No comments: