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

Related

  • The Power of Refactoring: Extracting Interfaces for Flexible Code
  • Design Pattern: What You Need to Know to Improve Your Code Effectively
  • Prototype Pattern in JavaScript
  • Object Relational Behavioral Design Patterns in Java

Trending

  • Architecting Zero-Trust AI Agents: How to Handle Data Safely
  • Agentic Testing: Moving Quality From Checkpoint to Control Layer
  • Building a DevOps-Ready Internal Developer Platform: A Hands-On Guide to Golden Paths, Self-Service, and Automated Delivery Pipelines
  • A Practical Blueprint for Deploying Agentic Solutions
  1. DZone
  2. Coding
  3. Languages
  4. Abstract Factory Design Pattern

Abstract Factory Design Pattern

Want to learn more about the abstract factory design pattern? Check out this tutorial about using the abstract pattern in your Java projects.

By 
Yogen Rai user avatar
Yogen Rai
·
Updated Nov. 06, 18 · Tutorial
Likes (9)
Comment
Save
Tweet
Share
46.8K Views

Join the DZone community and get the full member experience.

Join For Free

The abstract factory pattern has an interface that is responsible for creating a factory of related objects without explicitly specifying their classes. Each generated factory can give the objects as per the factory method pattern.

An abstract factory pattern is also called the Factory of Factories or Kit. In other words, this pattern has a super-factory that creates other factories This design pattern comes under the creational pattern as it provides one of the best ways to create an object.

The intent of this pattern, according to Design Patterns by Gamma et al, is to:

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

This pattern provides a level of indirection that abstracts the creation of families of related or dependent objects without directly specifying their concrete classes. The "factory" object has the responsibility for providing creative services for the entire platform family. Clients use the factory pattern to create platform objects but never create them directly.

Structure

The structure of factory method pattern is as shown in the figure below:

abstract-factory-pattern-structure

Figure: Abstract Factory Pattern Structure

The following classes are the participants of this pattern:

  •  AbstractFactory — declares an interface for operations that create abstract products.
  •  ConcreteFactory — implements operations to create concrete products.
  •  AbstractProduct — declares an interface for a type of product objects.
  •  Product — defines a product to be created by the corresponding ConcreteFactory; it implements the AbstractProduct interface.
  •  Client — uses the interfaces declared by the AbstractFactory and AbstractProduct classes.

Example

Let us modify an application from the factory method pattern, which draws different geometric shapes, this time including 2D or 3D, on the basis of client demand. The class diagram of the application is as shown below:

abstract-factory-pattern-example

Figure: Abstract Factory Method Example

Here, the FactoryProvider provides factories on the basis of the name provided by the client ( application.java in this case). With this factory object, we obtain the corresponding geometric shape, which we'll use to draw the shape.

Java Implementation

In order to implement the above-mentioned design, let's start with the GeometricShape interface.

/**
 * Product interface
 */
public interface GeometricShape {
    void draw();
}


The concrete implementations of the above interface are:

Line.java

/**
 * Concrete Product
 */
public class Line implements GeometricShape {
    @Override
    public void draw() {
        System.out.println("Line Drawn.");
    }
}


Circle.java

/**
 * Concrete product
 */
public class Circle implements GeometricShape {
    @Override
    public void draw() {
        System.out.println("Circle is drawn.");
    }
}


Sphere.java

/**
 * Concrete product
 */
public class Sphere implements GeometricShape {
    @Override
    public void draw() {
        System.out.println("Sphere drawn.");
    }
}


I have added following enums to name the factories as well as shapes:

public enum FactoryType {    
  TWO_D_SHAPE_FACTORY,    
  THREE_D_SHAPE_FACTORY
}

public enum  ShapeType {
    LINE,
    CIRCLE,
    SPHERE
}

Now, let's create the AbstractFactory.

/**
 * Abstract Factory
 */
public abstract class AbstractFactory {
    abstract GeometricShape getShape(ShapeType name);
}


The concrete classes for factories are:

TwoDShapeFactory.java

/**
 * Concrete factory
 */
public class TwoDShapeFactory extends AbstractFactory {
    @Override
    GeometricShape getShape(ShapeType name) {
        if (ShapeType.LINE == name) {
            return new Line();
        } else if (ShapeType.CIRCLE == name) {
            return new Circle();
        }
        return null;
    }
}


ThreeDShapeFactory.java

/**
 * Concrete factory
 */
public class ThreeDShapeFactory extends AbstractFactory {
    @Override
    GeometricShape getShape(ShapeType name) {
        if (ShapeType.SPHERE == name) {
            return new Sphere();
        }
        return null;
    }
}


The FactoryProvider class is:

/**
 * Factory provider
 */
public class FactoryProvider {
    public static AbstractFactory getFactory(FactoryType factoryType) {
        if (FactoryType.TWO_D_SHAPE_FACTORY == factoryType) {
            return new TwoDShapeFactory();
        } else if (FactoryType.THREE_D_SHAPE_FACTORY == factoryType) {
            return new ThreeDShapeFactory();
        }
        return null;
    }
}


Finally, the code for the client of this application is:

/**
 * Client
 */
public class Application {
    public static void main(String[] args) {
        //drawing 2D shape
        AbstractFactory factory = FactoryProvider.getFactory(TWO_D_SHAPE_FACTORY);
        if (factory == null) {
            System.out.println("Factory for given name doesn't exist.");
            System.exit(1);
        }
        //getting shape using factory obtained
        GeometricShape shape = factory.getShape(ShapeType.LINE);
        if (shape != null) {
            shape.draw();
        } else {
            System.out.println("Shape with given name doesn't exist.");
        }

        //drawing 3D shape
        factory = FactoryProvider.getFactory(THREE_D_SHAPE_FACTORY);
        if (factory == null) {
            System.out.println("Factory for given name doesn't exist.");
            System.exit(1);
        }
        //getting shape using factory obtained
        shape = factory.getShape(ShapeType.SPHERE);
        if (shape != null) {
            shape.draw();
        } else {
            System.out.println("Shape with given name doesn't exist.");
        }
    }
}


The output of the program is:

Line Drawn.
Sphere drawn.


The output shows that the factory corresponding to shape is required, which, in turn, is used to create an object.

Conclusion

This post talked about the summarized form of the Abstract Factory Method, as one of the GOF patterns, with a simple example. 

The source code for all example presented above is available on GitHub.

Happy coding!

Factory (object-oriented programming) Design Abstract factory pattern Object (computer science) Interface (computing)

Opinions expressed by DZone contributors are their own.

Related

  • The Power of Refactoring: Extracting Interfaces for Flexible Code
  • Design Pattern: What You Need to Know to Improve Your Code Effectively
  • Prototype Pattern in JavaScript
  • Object Relational Behavioral Design Patterns in Java

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook