02 Dec 2023
Intermediate
The Abstract Factory Pattern is a creational design pattern that provides an interface for creating families of related or dependent objects without specifying their concrete classes. In C#, the main components of the Abstract Factory Pattern include:
-
Abstract Product Interfaces:
- Declare interfaces for each product type. These interfaces define the operations that concrete product classes must implement.
public interface IProductA { void OperationA(); } public interface IProductB { void OperationB(); } -
Concrete Product Classes:
- Implement concrete product classes that implement the interfaces defined for each product type.
public class ConcreteProductA1 : IProductA { public void OperationA() { Console.WriteLine("ConcreteProductA1 OperationA"); } } public class ConcreteProductB1 : IProductB { public void OperationB() { Console.WriteLine("ConcreteProductB1 OperationB"); } } // Similar classes for ConcreteProductA2 and ConcreteProductB2 -
Abstract Factory Interface:
- Define an abstract factory interface that declares a set of creation methods for each type of product within a family of products.
public interface IAbstractFactory { IProductA CreateProductA(); IProductB CreateProductB(); } -
Concrete Factories:
- Implement concrete factory classes that implement the abstract factory interface. Each concrete factory is responsible for creating a family of related products.
public class ConcreteFactory1 : IAbstractFactory { public IProductA CreateProductA() { return new ConcreteProductA1(); } public IProductB CreateProductB() { return new ConcreteProductB1(); } } public class ConcreteFactory2 : IAbstractFactory { public IProductA CreateProductA() { return new ConcreteProductA2(); } public IProductB CreateProductB() { return new ConcreteProductB2(); } } -
Client Code:
- The client code uses the abstract factory interface to create families of related products without specifying their concrete classes.
public class Client { private IAbstractFactory factory; public Client(IAbstractFactory factory) { this.factory = factory; } public void Run() { var productA = factory.CreateProductA(); var productB = factory.CreateProductB(); productA.OperationA(); productB.OperationB(); } }
Usage:
class Program
{
static void Main()
{
// Create a client with ConcreteFactory1
Client client1 = new Client(new ConcreteFactory1());
client1.Run();
// Create a client with ConcreteFactory2
Client client2 = new Client(new ConcreteFactory2());
client2.Run();
}
}
Using the Abstract Factory Pattern allows for the creation of product families that are consistent with each other, making it easier to interchange them without affecting the client code.