DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Low-Code Development: Leverage low and no code to streamline your workflow so that you can focus on higher priorities.

DZone Security Research: Tell us your top security strategies in 2024, influence our research, and enter for a chance to win $!

Launch your software development career: Dive head first into the SDLC and learn how to build high-quality software and teams.

Open Source Migration Practices and Patterns: Explore key traits of migrating open-source software and its impact on software development.

Related

  • Bridge Design Pattern in Java: An Intro, Real-time Examples, Class/Seq Diagram, and Implementation
  • Adapter Design Pattern in Java - Introduction, Class/Sequence Diagram, and Implementation
  • Service Locator Design Pattern in Java: An Introduction, Class/Sequence Diagram, and Implementation
  • Spring Beans With Auto-Generated Implementations: How-To

Trending

  • Integration Testing With Keycloak, Spring Security, Spring Boot, and Spock Framework
  • Leveraging Microsoft Graph API for Unified Data Access and Insights
  • Front-End Application Performance Monitoring (APM)
  • Performance and Scalability Analysis of Redis and Memcached
  1. DZone
  2. Data Engineering
  3. Data
  4. Abstract Factory Pattern Tutorial with Java Examples

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

By 
James Sugrue user avatar
James Sugrue
DZone Core CORE ·
Feb. 23, 10 · Tutorial
Like (15)
Save
Tweet
Share
265.8K Views

Join the DZone community and get the full member experience.

Join For Free

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 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

  • Learn The Abstract Factory Pattern
  • Learn The Builder Pattern
  • Learn The Factory Method Pattern
  • Learn The Prototype Pattern

Structural Patterns

  • Learn The Adapter Pattern
  • Learn The Bridge Pattern
  • Learn The Decorator Pattern
  • Learn The Facade Pattern
  • Learn The Proxy Pattern

Behavioral Patterns

  • Learn The Chain of Responsibility Pattern
  • Learn The Command Pattern
  • Learn The Interpreter Pattern
  • Learn The Iterator Pattern
  • Learn The Mediator Pattern
  • Learn The Memento Pattern
  • Learn The Observer Pattern
  • Learn The State Pattern
  • Learn The Strategy Pattern
  • Learn The Template Method Pattern
  • Learn The Visitor Pattern


Factory (object-oriented programming) Abstract factory pattern Java (programming language) Implementation Factory method pattern Interface (computing) Class diagram Diagram Template method pattern

Opinions expressed by DZone contributors are their own.

Related

  • Bridge Design Pattern in Java: An Intro, Real-time Examples, Class/Seq Diagram, and Implementation
  • Adapter Design Pattern in Java - Introduction, Class/Sequence Diagram, and Implementation
  • Service Locator Design Pattern in Java: An Introduction, Class/Sequence Diagram, and Implementation
  • Spring Beans With Auto-Generated Implementations: How-To

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: