Abstract Factory Pattern

  • GoF:
  • Wiki:
  • Other:

Concepts

  • Factory of Factories
  • Factory of related Objects
  • Common Interface
  • Defer to subclasses for instantiation
  • Examples
    • DocumentBuilderFactory
    • Mostly in frameworks

Design Considerations

  • Groups Factories Together
  • Factory is responsible for lifecycle of itself
  • Common Interface
  • Concrete classes are returned from the underlying factory
  • Parameterized create method like factory pattern
  • Built using composition, not the case with Factory.

Example/Demo

  • Create classes that will be used
  • Build AbstractFactory
  • Then build Factory as it will be used by abstractfactory
  • Factory returns concrete implementation

Flow

CreditCardFactory (Abstract Factory)
- static CreditCardFactory getCreditCardFactory(int creditScore)
- abstract CreditCard getCreditCard(CardType cardType);
- abstract Validator getValidator(CardType cardType);
___________________________________|_________________________________
| |
AmexFactory (extends CreditCardFactory) VisaFactory (extends CreditCardFactory)
public CreditCard getCreditCard(CardType cardType) {
switch (cardType) {
case GOLD:
return new AmexGoldCreditCard();
case PLATINUM:
return new AmexPlatinumCreditCard();
}
}
public Validator getValidator(CardType cardType) {
switch (cardType) {
case GOLD:
return new AmexGoldValidator();
case PLATINUM:
return new AmexPlatinumValidator();
}
}

if you are not using the ORM and you have to use the db queries depending on the db you are using, this pattern will find implementation their.

Drawbacks

  • Complexity - most complex of creational design patterns
  • Runtime Switch - cleenct can change the flow by passing some parameters
  • Pattern within a pattern
  • Problem specific (limited scope)
  • Starts as a factory and the refactored to abstractFactory

Contrast to other patterns

FactoryAbstractFactory
Returns various instancesImplemented with a factory
- multiple constructorsHides the underlying concrete factory
Interface Driven1 more layer of Abstraction added to environment
Adaptable to environment more easilyBuilt through composition

Summary

  • Group of similar factories
  • Complex
  • Heavy abstraction
  • Written at framework level