Factory Method Pattern

Understanding the Factory Method

Welcome back! We have already covered the Singleton pattern and how it ensures a class has only one instance. Now, let's dive into another essential creational design pattern: the Factory Method pattern. This lesson will guide you through understanding the Factory Method pattern, a powerful tool used to define an interface for creating an object but allows subclasses to alter the type of objects that will be created.

What You'll Learn

In this lesson, you'll gain a solid understanding of the Factory Method pattern in Java. We will focus on:

  • What the Factory Method pattern is and why it is used.
  • How to implement the Factory Method pattern using a factory class.
  • Creating different types of document classes (WordDocument and ExcelDocument) and generating their instances via the factory method.

The Factory Pattern

The Factory Method pattern is a creational design pattern that provides an interface for creating objects in a superclass but allows subclasses to alter the type of objects that will be created. Instead of calling a constructor directly to create an object, the client calls a factory method defined by an abstract class or interface, which delegates the process to derived classes. This approach promotes loose coupling and adheres to the Open/Closed Principle, allowing a system to be extended without modifying existing code.

We'll walk through a code example involving Document, WordDocument, and ExcelDocument classes, managed by a DocumentFactory class.

Step 1: Define the Document Class

First, we define an abstract class for our documents.

public abstract class Document {
    // Abstract method to be implemented by concrete document types
    public abstract void open();
}

The Document abstract class declares an abstract method open that all document types must implement. This provides a common contract for all documents.

Step 2: Implement Concrete Document Classes

We create two concrete implementations of the Document class, WordDocument and ExcelDocument.

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

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

WordDocument and ExcelDocument classes extend the Document class, thereby providing specific behavior for opening Word and Excel documents respectively.

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