abstract factory in csharp

The Abstract Factory pattern provides an interface for creating families of related objects without specifying their concrete classes. It is a creational pattern and falls under the category of object-oriented design patterns.

Here's an example implementation of the Abstract Factory pattern in C#:

main.cs
// Define the product interface
public interface IProduct
{
    string GetName();
}

// Define the concrete product classes
public class ProductA : IProduct
{
    public string GetName() => "Product A";
}

public class ProductB : IProduct
{
    public string GetName() => "Product B";
}

// Define the factory interface
public interface IFactory
{
    IProduct CreateProduct();
}

// Define the concrete factory classes
public class FactoryA : IFactory
{
    public IProduct CreateProduct() => new ProductA();
}

public class FactoryB : IFactory
{
    public IProduct CreateProduct() => new ProductB();
}

// Use the factories to create instances of the products
public class Client
{
    private IFactory factory;

    public Client(IFactory factory)
    {
        this.factory = factory;
    }

    public void UseProduct()
    {
        var product = factory.CreateProduct();
        var productName = product.GetName();
        Console.WriteLine($"Using {productName}");
    }
}

// Example usage
var clientA = new Client(new FactoryA());
clientA.UseProduct(); // Output: Using Product A

var clientB = new Client(new FactoryB());
clientB.UseProduct(); // Output: Using Product B
1184 chars
59 lines

In this example, we have two concrete product classes (ProductA and ProductB) and two concrete factory classes (FactoryA and FactoryB). The Client class takes an instance of an IFactory during construction, and then uses this factory to create an instance of the relevant product (ProductA or ProductB). This allows the client to use different products without having to worry about their concrete classes.

gistlibby LogSnag