Introduction

In our previous article, "Categorizing Design Patterns: Creational, Structural, and Behavioral", we categorized design patterns into three main types: Creational, Structural, and Behavioral. We provided an overview of each category, including their purposes and real-world examples.

In this article, we will focus on The Factory Method Pattern. The Factory Method Pattern is a creational design pattern that provides a way to delegate the responsibility of creating objects to subclasses. This pattern simplifies object creation by decoupling the client code from the specific classes that need to be instantiated, making the code more flexible and maintainable.

Understanding the Factory Method Pattern

The Factory Method Pattern defines an interface for creating an object but allows subclasses to decide which class to instantiate. This approach helps reduce tight coupling between the client code and the concrete classes, enhancing flexibility and scalability.

Key Components

Example in C#

Let's illustrate the Factory Method Pattern with a practical example involving document creation. Create two folders in your project Documents and Factories.

1. Define the Product Interface Under Document Folder

IDocument.cs

namespace Factory_Method_Pattern_Demo.Documents
{
    public interface IDocument
    {
        void Open();
        void Close();
    }
}

Explanation

2. Implement Concrete Products Class under the document folder

WordDocument.cs

namespace Factory_Method_Pattern_Demo.Documents
{
    public class WordDocument : IDocument
    {
        public void Open() => Console.WriteLine("Opening Word Document.");
        public void Close() => Console.WriteLine("Closing Word Document.");
    }
}

Explanation

PdfDocument.cs

namespace Factory_Method_Pattern_Demo.Documents
{
    public class PdfDocument : IDocument
    {
        public void Open() => Console.WriteLine("Opening PDF Document.");
        public void Close() => Console.WriteLine("Closing PDF Document.");
    }
}

Explanation

3. Create the Creator Base Class: Abstract Factory Under the Factories Folder

DocumentFactory.cs

namespace Factory_Method_Pattern_Demo.Factories
{
    using Factory_Method_Pattern_Demo.Documents;

    public abstract class DocumentFactory
    {
        public abstract IDocument CreateDocument();
        public void OpenDocument()
        {
            var document = CreateDocument();
            document.Open();
        }
        public void CloseDocument()
        {
            var document = CreateDocument();
            document.Close();
        }
    }
}

Explanation

4. Implement Concrete Products Class under the Factories Folder

WordDocumentFactory.cs

namespace Factory_Method_Pattern_Demo.Factories
{
    using Factory_Method_Pattern_Demo.Documents;
    public class WordDocumentFactory : DocumentFactory
    {
        public override IDocument CreateDocument() => new WordDocument();
    }
}

Explanation

PdfDocumentFactory.cs

namespace Factory_Method_Pattern_Demo.Factories
{
    using Factory_Method_Pattern_Demo.Documents;

    public class PdfDocumentFactory : DocumentFactory
    {
        public override IDocument CreateDocument() => new PdfDocument();
    }
}

Explanation:

5. Client Code

Program. cs

using Factory_Method_Pattern_Demo.Factories;

class Program
{
    static void Main(string[] args)
    {
        DocumentFactory factory;
        Console.WriteLine("Enter the type of document to create (Word/PDF):");
        var input = Console.ReadLine();
        switch (input.ToLower())
        {
            case "word":
                factory = new WordDocumentFactory();
                break;
            case "pdf":
                factory = new PdfDocumentFactory();
                break;
            default:
                throw new ArgumentException("Invalid document type");
        }
        factory.OpenDocument();
        factory.CloseDocument();
    }
}

Explanation

File Structure For the Above Example.

File structure

Output

Output

Visual Studio

Real-World Use Cases

The Factory Method Pattern is widely used in various scenarios.

Benefits

Summary

The Factory Method Pattern simplifies object creation by delegating it to subclasses, thus promoting flexibility, encapsulation, and scalability. This pattern is particularly useful when dealing with complex object-creation processes and can significantly enhance the maintainability of the code.

Next Steps

In the next article, we will explore "Abstract Factory Pattern: Designing Families of Related Objects". This pattern extends the Factory Method Pattern to create families of related objects, and we will discuss its components, practical implementations, and real-world applications to illustrate its use in .NET Core projects.
Feel free to adjust or expand upon this content as needed for your specific audience and context!

If you find this article valuable, please consider liking it and sharing your thoughts in the comments.

Thank you, and happy coding.