Composite Factory Design Pattern


Here, we will explain Composite Factory Design Pattern with example in C#. This pattern allows you to create complex objects and manage hierarchical structures of these objects with ease. Here is a detailed overview.

Composite Factory Design Pattern

The Composite Factory Pattern is a combines the principles of the Composite pattern and the Factory pattern. It allows you to create and manage complex tree-like structures of objects, where each node can be either a leaf or a composite of other nodes. The Factory pattern facilitates the creation of these nodes, managing object creation at various levels of the hierarchy.

Example - File Systems

In a file system, directories can contain files and other directories, creating a hierarchical structure. The Composite Factory Pattern helps manage this hierarchy by providing a unified way to create and manage files and directories. We will explain in detail lator part of the article.

CompositeFactory Design Pattern

Advantages of the Composite Factory Pattern

  • Unified Object Creation - Simplifies object creation by centralizing the logic in factories, making it easier to manage complex hierarchies.
  • Flexibility - Allows for dynamic composition of objects. You can easily add or remove components without altering the code that uses the composite structure.
  • Scalability - Facilitates scaling by providing a consistent way to create and manage objects in a hierarchy.
  • Maintenance - Enhances code maintainability by separating the creation logic from the business logic, making it easier to modify or extend the hierarchy.

When to Use the Composite Factory Pattern

  • Hierarchical Structures - When dealing with complex hierarchical structures where components can be both individual objects and compositions of other objects.
  • Complex Object Creation - When you need to manage the creation of objects that form a tree-like structure with varying complexity.
  • Dynamic Composition - When the composition of objects can change at runtime and you need a flexible way to create and manage these changes.

Problems with a System Without Composite Factory

  • Tight Coupling - Without a Composite Factory, object creation logic is often scattered across the codebase, leading to tight coupling between object creation and business logic.
  • Complexity - Managing complex hierarchical structures becomes challenging without a centralized creation mechanism, making the system harder to understand and maintain.
  • Scalability Issues - Adding new types or changing existing types requires modifications in multiple places, which can lead to errors and increased maintenance effort.

Real-World Example - File Systems

In a file system, directories can contain files and other directories, creating a hierarchical structure. The Composite Factory Pattern helps manage this hierarchy by providing a unified way to create and manage files and directories.

Let's consider a file system where File and Directory are components. A Directory can contain other Files or Directories, and the CompositeFactory is used to create these components.

using System;
using System.Collections.Generic;

// Component
public abstract class FileSystemComponent
{
    public abstract void Display(int indent = 0);
}

// Leaf
public class File : FileSystemComponent
{
    private string _name;

    public File(string name)
    {
        _name = name;
    }

    public override void Display(int indent = 0)
    {
        Console.WriteLine(new String(' ', indent) + "File: " + _name);
    }
}

// Composite
public class Directory : FileSystemComponent
{
    private string _name;
    private List<FileSystemComponent> _components = new List<FileSystemComponent>();

    public Directory(string name)
    {
        _name = name;
    }

    public void Add(FileSystemComponent component)
    {
        _components.Add(component);
    }

    public override void Display(int indent = 0)
    {
        Console.WriteLine(new String(' ', indent) + "Directory: " + _name);
        foreach (var component in _components)
        {
            component.Display(indent + 2);
        }
    }
}

// Factory
public static class CompositeFactory
{
    public static FileSystemComponent CreateFile(string name)
    {
        return new File(name);
    }

    public static FileSystemComponent CreateDirectory(string name)
    {
        return new Directory(name);
    }
}

// Example usage
class Program
{
    static void Main()
    {
        // Create files
        var file1 = CompositeFactory.CreateFile("file1.txt");
        var file2 = CompositeFactory.CreateFile("file2.txt");

        // Create directories
        var dir1 = (Directory)CompositeFactory.CreateDirectory("dir1");
        var dir2 = (Directory)CompositeFactory.CreateDirectory("dir2");

        // Add files to directories
        dir1.Add(file1);
        dir1.Add(file2);

        // Create a nested directory
        var nestedDir = (Directory)CompositeFactory.CreateDirectory("nestedDir");
        nestedDir.Add(CompositeFactory.CreateFile("nestedFile1.txt"));

        // Add nested directory to dir2
        dir2.Add(nestedDir);

        // Display the hierarchy
        Console.WriteLine("File System Structure:");
        dir1.Display();
        dir2.Display();
    }
}

Explanation

  • FileSystemComponent - This is the abstract base class for both File and Directory. It defines the Display method, which can be overridden to display the component's details.
  • File - Represents a leaf in the hierarchy. It has a name and implements the Display method to show its name.
  • Directory - Represents a composite node in the hierarchy. It can contain other FileSystemComponent objects, either Files or other Directories. It also implements the Display method to show its name and recursively display its contents.
  • CompositeFactory - Provides static methods to create File and Directory instances. This factory centralizes the creation logic.
  • Program - Demonstrates how to use the CompositeFactory to create a file system structure and display it.

Output

CompositeFactory Design Pattern

Application of Composite Factory Design Pattern

  • Document Editors - Managing different types of content (text, images, tables) in a document editor where each type of content can be composed of other content types.
  • Organization Structures - Creating and managing hierarchical structures like organizational charts where each node can be an individual employee or a department consisting of other employees or departments.
  • Configuration Systems - Building configuration systems where settings can be grouped hierarchically, and each group or setting can be created and managed consistently.

Prev Next

Top Articles

  1. What is JSON
  2. How to convert a javaScript object in JSON object
  3. Some Important JSON Examples
  4. Common JSON Interview Question