I've been a zone leader with DZone since 2008, and I'm crazy about community. Every day I get to work with the best that JavaScript, HTML5, Android and iOS has to offer, creating apps that truly make at difference, as principal front-end architect at Avego. James is a DZone Zone Leader and has posted 639 posts at DZone. You can read more from them at their website. View Full User Profile

Design Patterns Uncovered: The Abstract Factory Pattern

  • submit to reddit

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 industrial building where workers manufacture goods or supervise machines processing 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. The definition of Abstract Factory provided in the original Gang of Four book on Design Patterns 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.

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:

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: 

public class MSWindow implements Window
public void setTitle()
//MS Windows specific behaviour

public void repaint()
//MS Windows specific behaviour

And one for Mac OSX

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: 

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:

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

And for MacOSX:

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.

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
widgetFactory = new MacOSXWidgetFactory();
widgetFactory = new MsWindowsWidgetFactory();

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: 

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.

Other Articles in This Series
The Observer Pattern
The Adapter Pattern
The Facade Pattern
The Factory Method Pattern
The Abstract Factory Pattern
The Singleton Pattern
The Strategy Pattern
The Visitor Pattern

Next Up

I haven't decided which pattern I'll publish next, so this time I'll give you the chance to pick the next pattern in the series. Just leave a comment to let me know.



Robert Csala replied on Tue, 2010/02/23 - 4:29am

Why are the concrete factories interfaces? Copy/Paste?

James Sugrue replied on Tue, 2010/02/23 - 5:41am in response to: Robert Csala

Thanks for spotting that - should be fixed now


Robert Csala replied on Tue, 2010/02/23 - 9:49am

Good article, btw. Simple, to the point.

Robert Csala replied on Tue, 2010/02/23 - 10:08am

In a sense, isn't this just a combined Facade and Factory pattern?

Ratheesh Kumar replied on Tue, 2010/02/23 - 11:57am

please write about the proxy pattern next

Nana Noop replied on Tue, 2010/02/23 - 1:25pm

Great article.  Can you make your article printable, instead of just their code?

Nana Noop replied on Tue, 2010/02/23 - 1:31pm

Oops, my bad.  Missed the "printer friendly" link.

Gilbert Herschberger replied on Tue, 2010/02/23 - 3:34pm

there's one thing that annoys me

You say that it annoys you to see an inelegant switch statement in the middle of your otherwise clean example. It annoys me too. Here is why.

We have learned from our study of design patterns that a switch statement might be an indication of an incomplete design. So, we go back to our collection of design patterns and look for a pattern to apply. Ignoring for a moment that we are working with a factory class, what pattern would we normally apply to select one of several implementation classes at runtime? A factory method or an abstract factory. Therefore, the pattern is recursive.

Guido Amabili replied on Tue, 2010/02/23 - 4:01pm

I would like to read about the visitor pattern.

Vedhas Pitkar replied on Thu, 2010/02/25 - 12:19am

Is there any way of avoiding the switch statement for creating the concrete classes? The same thing can be done with the Factory pattern so where would I use either of the two? There's a small typo: "The definition of Singleton" before the GOF diagram.

jawed ahmed replied on Thu, 2010/02/25 - 5:33am

i think AbstractFactory should be implemented by ConcreteFactories...

Gilbert Herschberger replied on Mon, 2010/03/01 - 4:00pm

A platform-dependent example might help to understand how to eliminate the switch statement when choosing a concrete factory. We would agree that a running Java application is running either Linux or Windows, but not both. Let's say that we have two platform-dependent jars, XL.jar for Linux and XW.jar for Windows.

How do we want our application to work? Do we install one jar or the other, but not both? Do we install both jars and determine which jar to use at runtime?

In the first scenario, the concrete factory is determined at install-time, or deploy-time. We install one jar or the other. We use the same name for all custom implementations of the concrete factory. We choose an implementation by choosing which jar to install. We install XL.jar only on Linux and XW.jar only on Windows.

In the second scenario, the concrete factory is determined at runtime, or loadtime. We install both jars. We use different names for the concrete factory. For Linux, it might be LinuxConcreteFactory. For Windows, it might be WindowsConcreteFactory. By choosing to use different names, we could resort to a switch statement to choose one at runtime.

On the other hand, the fully qualified name of the concrete factory can be typed on the command line. This is a quick-and-dirty technique. The -D command line option enables you to set a custom property. Use a custom property to identify a concrete factory.

For a platform-specific class, the name of the class can be computed, in other words, based upon a system property for the current operating system. A resource called META-INF/service/widget-linux, for example, might contain the fully qualified name of the concrete factory for Linux.

There is yet another approach. Use a well-known resource, such as META-INF/service/name, to identify a concrete factory. Multiple resources contain the fully qualified name of the concrete factory. All are called META-INF/service/widget, for example.

These are a few techniques. There are others.

John Turner replied on Wed, 2010/03/31 - 8:20am

Good example Gilbert.  The concrete implemenation is commonly determined once (at startup for instance).

Even if the concrete implementation is determined at runtime and this is determined with a switch statement, you are still reducing the number of switch statements.  You are deciding which family of Product to create in a single place rather that which Product to create in multiple places.


Zsolt Kúti replied on Sun, 2010/04/18 - 2:32pm

Sometimes selection of the concrete factory at runtime unavoidably requires switch/if statements. To have only a few of them is still much more acceptable than the plenty one which the pattern helps to avoid: the main merit of a factory truly shines when there are many classes of objects to be created by a factory and several different factories are required.

Darren Martin replied on Fri, 2014/04/25 - 10:36am

Still looking forward that they work on adding multiple pattern.

Darren "designer for http://www.digiteksf.com/digital-color-copies/"

Marving Gay replied on Tue, 2014/07/15 - 8:58am

I am new to java and am trying to understand design patterns. Please be patientCould it be that the code was wrong?  Could it be?
// ConcreteProductA1
	public void setTitle()
// ConcreteProductA2
	public void setTitle()
should be?
public void setTitle(String text) 
{ // code 
The next one
// ConcreteFactory1
class MsWindowsWidgetFactory 
// ConcreteFactory2
class MacOSXWidgetFactory 
should be?
// ConcreteFactory1
class MsWindowsWidgetFactory implements AbstractWidgetFactory
// ConcreteFactory2
class MacOSXWidgetFactory implements AbstractWidgetFactory
Remember:I am new to java and am trying to understand design patterns. Please be patient

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.