About me
Services
Projects
Design Patterns
Archive
Contact
home > Design Patterns > The Abstract Factory Pattern.

The Abstract Factory Pattern

Just imagine it, a Factory spitting out custom 1's and 0's organized by you, the designer. Just the name of it conjures images of utility and engineering, well for me it does. Could be my Mechanical Engineering degree, but the Factory Pattern just makes sense. When creating a class that has to support slightly different implementations, the Factory Pattern helps to reduce coupling of the concrete class to the code. Because the Factory produces an interface for the object being created, it adheres to the design principle of Code to the interface, not the implementation. Use the Abstract Factory Pattern and watch your code become more robust, extensible and maintainable.

The Abstract Factory Defined

Intent: Provide an interface for creating families of related or dependent objects without specifying their concrete classes. -GoF

The Simple Factory

Lets start with an example of a Simple Factory, we will save the Abstract till later.

public class CarFactory {

  public Ford createFord(String model) {
    
    Ford ford = null;
    
    if (model.equals("Focus")) {
      ford = new Focus();
    else if (model.equals("Fusion")) {
      ford = new Fusion();
    else if (model.equals("Mustang")) {
      ford = new Mustang();
    else if (model.equals("Taurus")) {
      ford = new Taurus();
    else if (model.equals("Shelby GT500")) {
      ford = new Shelby();
    }
    return ford;
  }
}

The main thing to note in this code example is that Ford is an interface and is being implemented by all of the ford models, Focus, Fusion, Mustang, Taurus and Shelby. What is being returned is the interface and not the concrete class. What we have done is encapsulated the creation of the ford car in one class. So, now when a new model is released or is no longer available we only have to make changes to the code in one place. Any instantiations of the Ford implementation should be removed from the code.

So that defines the Simple Factory, so how do we create an Abstract Factory?

The Abstract Factory

The simple Factory defined above is, well... Simple. Lets have a closer look at the calling code to see just how the Factory is being used.

public class FordDealer {

  CarFactory factory = new CarFactory();
  
  public Ford OrderFord(String model) {
    
    Ford ford = factory.createFord(model);
    
    return ford;
  }
}

Conclusion

The Abstract Factory is a very powerful and popular design pattern.

Good luck!
Copyright 2008 Graham Lange All rights reserved
SUBSCRIBE