Over a million developers have joined DZone.
Silver Partner

Abstract Factory Pattern Tutorial with Java Examples

Learn the Abstract Factory Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered

· Java Zone

Having gone through the Factory Method pattern in the last article in this series, today we'll take a look at Abstract Factory, the other factory pattern. 

Factories in the Real World 

It's easy to think of factories in the real world - a factory is just somewhere that items gets produced such as cars, computers or TVs. Wikipedia's definition of a real world factory is: 

A factory (previously manufactory) or manufacturing plant is an industrialbuilding where workers manufacturegoods or supervise machinesprocessing one product into another.

It's pretty clear what a factory does, so how does the pattern work?

Design Patterns Refcard
For a great overview of the most popular design patterns, DZone's Design Patterns Refcard is the best place to start. 

The Abstract Factory Pattern

The Abstract Factory is known as a creational pattern - it's used to construct objects such that they can be decoupled from the implementing system. Thedefinition of Abstract Factory provided in the original Gang of Four book on DesignPatterns states: 

Provides an interface for creating families of related or dependent objects without specifying their concrete classes.

Now, let's take a look at the diagram definition of the Abstract Factory pattern.

Image title


Although the concept is fairly simple, there's a lot going on in this diagram. I've used red to note the different between what ConcreteFactory2 is responsible for. 

The AbstractFactory defines the interface that all of the concrete factories will need to implement in order to product Products. ConcreteFactoryA and ConcreteFactoryB have both implemented this interface here, creating two seperate families of product. Meanwhile, AbstractProductA and AbstractProductB are interfaces for the different types of product. Each factory will create one of each of these AbstractProducts. 

The Client deals with AbstractFactory, AbstractProductA and AbstractProductB. It doesn't know anything about the implementations. The actual implementation of AbstractFactory that the Client uses is determined at runtime.

As you can see, one of the main benefits of this pattern is that the client is totally decoupled from the concrete products. Also, new product families can be easily added into the system, by just adding in a new type of ConcreteFactory that implements AbstractFactory, and creating the specific Product implementations.

For completeness, let's model the Clients interactions in a sequence diagram:

Image title


While the class diagram looked a bit busy, the sequence diagram shows how simple this pattern is from the Clients point of view. The client has no need to worry about what implementations are lying behind the interfaces, protecting them from change further down the line.

Where Would I Use This Pattern?

The pattern is best utilised when your system has to create multiple families of products or you want to provide a library of products without exposing the implementation details. As you'll have noticed, a key characteristic is that the pattern will decouple the concrete classes from the client. 

An example of an Abstract Factory in use could be UI toolkits. Across Windows, Mac and Linux, UI composites such as windows, buttons and textfields are all provided in a widget API like SWT. However, the implementation of these widgets vary across platforms. You could write a platform independent client thanks to the Abstract Factory implementation. 

So How Does It Work In Java?

Let's take the UI toolkit concept on to our Java code example. We'll create a client application that needs to create a window. 

First, we'll need to create our Window interface. Window is our AbstractProduct

//Our AbstractProduct
public interface Window{
  public void setTitle(String text);
  public void repaint();
}

Let's create two implementations of the Window, as our ConcreteProducts. One for Microsoft Windows: 

//ConcreteProductA1
public class MSWindow implements Window{
  public void setTitle(){
    //MS Windows specific behaviour
  }
  public void repaint(){
    //MS Windows specific behaviour
  }
}

And one for Mac OSX

//ConcreteProductA2
public class MacOSXWindow implements Window{
  public void setTitle(){
    //Mac OSX specific behaviour
  }
  public void repaint(){
    //Mac OSX specific behaviour
  }
}

Now we need to provide our factories. First we'll define our AbstractFactory. For this example, let's say they just create Windows: 

//AbstractFactory
public interface AbstractWidgetFactory{
  public Window createWindow();
}

Next we need to provide ConcreteFactory implementations of these factories for our two operating systems. First for MS Windows:

//ConcreteFactory1
public class MsWindowsWidgetFactory{
  //create an MSWindow
  public Window createWindow(){
    MSWindow window = new MSWindow();
    return window;
  }
}

And for MacOSX:

//ConcreteFactory2
public class MacOSXWidgetFactory{
  //create a MacOSXWindow
  public Window createWindow(){
    MacOSXWindow window = new MacOSXWindow();
    return window;
  }
}

Finally we need a client to take advantage of all this functionality.

//Client
public class GUIBuilder{
  public void buildWindow(AbstractWidgetFactory widgetFactory){
    Window window = widgetFactory.createWindow();
    window.setTitle("New Window");
  }
}

Of course, we need some way to specify which type of AbstractWidgetFactory to our GUIBuilder. This is usually done with a switch statement similar to the code below:

public class Main{
  public static void main(String[] args){
    GUIBuilder builder = new GUIBuilder();
    AbstractWidgetFactory widgetFactory = null;
    //check what platform we're on
    if(Platform.currentPlatform()=="MACOSX"){
      widgetFactory  = new MacOSXWidgetFactory();
    } else {
      widgetFactory  = new MsWindowsWidgetFactory();
    }
    builder.buildWindow(widgetFactory);
  }
}

Just to give a clear idea of how this implementation relates to the Abstract Factory pattern, here's a class diagram representing what we've just done: 

Image title


Watch Out for the Downsides

While the pattern does a great job of hiding implementation details from the client, there is always a chance that the underlying system will need to change. We may have new attributes to our AbstractProduct, or AbstractFactory, which would mean a change to the interface that the client was relying on, thus breaking the API.

With both the Factory Method and today's pattern, the Abstract Factory, there's one thing that annoys me - someone has to determine what type of factory the client is dealing with at runtime. As you see above, this is usually done with some type of switch statement.

The Whole "Design Patterns Uncovered" Series:

Creational Patterns

Structural Patterns

Behavioral Patterns


Topics:
java,design patterns,patterns,design patterns uncovered

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}