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

Migrate, Modernize and Build Java Web Apps on Azure: This live workshop will cover methods to enhance Java application development workflow.

Kubernetes in the Enterprise: The latest expert insights on scaling, serverless, Kubernetes-powered AI, cluster security, FinOps, and more.

A Guide to Continuous Integration and Deployment: Learn the fundamentals and understand the use of CI/CD in your apps.

Related

  • Composite Design Pattern in Java
  • Builder Design Pattern In Java
  • Iterator Design Pattern In Java
  • Factory Method Design Pattern

Trending

  • What Is CI/CD? Beginner’s Guide To Continuous Integration and Deployments
  • AWS Partition Projections: Enhancing Athena Query Performance
  • Top 10 Software Development Trends for 2024
  • Ensuring API Resilience in Spring Microservices Using Retry and Fallback Mechanisms
  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.

Yogen Rai user avatar by
Yogen Rai
·
Updated Nov. 06, 18 · Tutorial
Like (9)
Save
Tweet
Share
45.3K 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

  • Composite Design Pattern in Java
  • Builder Design Pattern In Java
  • Iterator Design Pattern In Java
  • Factory Method Design Pattern

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