Abstract Factory Pattern

Welcome to the Abstract Factory Pattern

Welcome back! After exploring the Factory Method pattern and how it allows you to create different types of objects through a common interface, we’re now ready to move on to the Abstract Factory pattern. This lesson will guide you through understanding the Abstract Factory pattern — a design pattern that provides an interface for creating families of related or dependent objects without specifying their concrete classes.

What You'll Learn

In this lesson, you’ll delve into the details of the Abstract Factory pattern. You will learn:

  • What the Abstract Factory pattern is and its purpose.
  • How to implement the Abstract Factory pattern to create different types of documents.
  • The distinction between Abstract Factory and Factory Method patterns.

Understanding the Abstract Factory

The Abstract Factory pattern is a creational design pattern that provides an interface for creating families of related or dependent objects without specifying their exact classes. This pattern encapsulates a group of individual factories that have a common theme and can be used to create objects that are designed to work together. By abstracting the creation process, the Abstract Factory pattern ensures that the client code remains unaware of the specific classes being instantiated, promoting loose coupling and enhancing code scalability and maintainability.

We'll explore a comprehensive code example featuring various types of documents such as WordDocument, ExcelDocument, GoogleDoc, and GoogleSheet. These document types will be instantiated using different concrete factories (WordDocumentFactory, ExcelDocumentFactory, etc.) managed by an abstract interface (DocumentAbstractFactory). This approach will give you a more flexible and scalable way to handle complex object structures.

Step 1: Define Abstract Products

Java
// Abstract Products
interface Document {
    void open();
}

class WordDocument implements Document {
    public void open() {
        System.out.println("Opening Word Document");
    }
}

class ExcelDocument implements Document {
    public void open() {
        System.out.println("Opening Excel Document");
    }
}

Here, we define the abstract product Document and its concrete implementations WordDocument and ExcelDocument. These classes implement the open method in their own way.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal