Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Simple Factory, Factory Method, and Abstract Factory Patterns in C#

Tech 1

Simple Factory, Factory Method, and Abstract Factory are fonudational creational design patterns that manage object instantiation. Simple Factory centralizes creation logic, Factory Method delegates it to subclasses, and Abstract Factory handles families of related objects.

Simple Factory Pattern This pattern uses a factory class to create objects based on input parameters, abstracting creation details from clients. It enhances encapsulation and flexibility. For example, in a calculator application, an operation base class is defined, with subclasses for specific operations like addition and subtraction. A factory class selects the appropriate subclass.

Define the operation base class:

public abstract class Calculation
{
    public double ValueX { get; set; }
    public double ValueY { get; set; }
    public abstract double Compute();
}

Implement subclasses for addition and subtraction:

public class Addition : Calculation
{
    public override double Compute()
    {
        return ValueX + ValueY;
    }
}

public class Subtraction : Calculation
{
    public override double Compute()
    {
        return ValueX - ValueY;
    }
}

Create a factory class to instantiate subclasses:

public class CalculationFactory
{
    public static Calculation GenerateCalculation(string operationType)
    {
        Calculation calc = null;
        switch (operationType)
        {
            case "add":
                calc = new Addition();
                break;
            case "subtract":
                calc = new Subtraction();
                break;
            default:
                calc = new Addition();
                break;
        }
        return calc;
    }
}

Client code uses the factory:

static void Main(string[] args)
{
    Calculation calc = CalculationFactory.GenerateCalculation("add");
    if (calc != null)
    {
        calc.ValueX = 5;
        calc.ValueY = 3;
        double outcome = calc.Compute();
    }
}

Factory Method Pattern This pattern defines an interface for creating objects, allowing subclasses to alter the type of objects instantiated. It addresses the open-closed principle by avoiding conditional logic in the factory. An interface is created for factories, with subclasses implementing it to produce specific objects.

Define the factory interface:

public interface ICalculationFactory
{
    Calculation CreateCalculation();
}

Implement factory subclasses:

public class AdditionFactory : ICalculationFactory
{
    public Calculation CreateCalculation()
    {
        return new Addition();
    }
}

public class SubtractionFactory : ICalculationFactory
{
    public Calculation CreateCalculation()
    {
        return new Subtraction();
    }
}

Client code selects a factory:

ICalculationFactory factory = new AdditionFactory();
Calculation calc = factory.CreateCalculation();
if (calc != null)
{
    calc.ValueX = 10;
    calc.ValueY = 4;
    double outcome = calc.Compute();
}

Comparison Simple Factory uses a single class with conditional logic, which can violate the open-closed principle when adding new types. Factory Method decentralizes creation by using an interface and subclasses, making it more extensible. Abstract Factory extends this to create families of related objects, though not detailed here.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.