DEV Community

Juarez Júnior for Develop4Us

Posted on • Edited on

C# Design Pattern: Factory Method

The Factory Method pattern is used to centralize object creation based on a choice or criterion. Instead of having multiple factory classes, you can have a single class responsible for creating different types of objects, such as documents, depending on the need. This is useful in situations where you need to create different formats of documents, such as PDF or Word, without modifying the main code every time a new format is added.

C# Code Example:

// Base product
public abstract class Document
{
    public abstract void Print();
}

// Concrete product 1
public class PdfDocument : Document
{
    public override void Print()
    {
        Console.WriteLine("Printing PDF document.");
    }
}

// Concrete product 2
public class WordDocument : Document
{
    public override void Print()
    {
        Console.WriteLine("Printing Word document.");
    }
}

// Centralized creator class
public class DocumentFactory
{
    public enum DocumentType
    {
        PDF,
        WORD
    }

    public Document CreateDocument(DocumentType type)
    {
        switch (type)
        {
            case DocumentType.PDF:
                return new PdfDocument();
            case DocumentType.WORD:
                return new WordDocument();
            default:
                throw new ArgumentException("Unknown document type.");
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        DocumentFactory factory = new DocumentFactory();

        // Create and print a PDF document
        Document doc = factory.CreateDocument(DocumentFactory.DocumentType.PDF);
        doc.Print();  // Output: Printing PDF document.

        // Create and print a Word document
        doc = factory.CreateDocument(DocumentFactory.DocumentType.WORD);
        doc.Print();  // Output: Printing Word document.
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

Here, the DocumentFactory class centralizes the creation of different types of documents (PDF and Word). The CreateDocument method takes a DocumentType enum parameter that defines which type of document to create. The method then creates and returns the correct instance based on that type. The main code shows how to dynamically create PDF or Word documents depending on the need.

Conclusion:

The Factory Method centralizes the creation of different object types, allowing the creation logic to be separated from the main code. This makes it easier to add new object types in the future without modifying existing code. It’s ideal for scenarios where object creation may vary based on different factors, such as user input or configurations.

Source code: GitHub

Top comments (0)