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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
Partner Zones AWS Cloud
by AWS Developer Relations
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
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  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

James Sugrue user avatar by
James Sugrue
CORE ·
Feb. 23, 10 · Tutorial
Like (15)
Save
Tweet
Share
264.58K 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 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

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

Structural Patterns

  • Learn The Adapter Pattern
  • Learn The Bridge Pattern
  • Learn The Composite Pattern
  • Learn The Decorator Pattern
  • Learn The Facade Pattern
  • Learn The Flyweight 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.

Popular on DZone

  • Important Takeaways for PostgreSQL Indexes
  • Beyond Coding: The 5 Must-Have Skills to Have If You Want to Become a Senior Programmer
  • Integrating AWS Secrets Manager With Spring Boot
  • How Agile Architecture Spikes Are Used in Shift-Left BDD

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: