추상 팩토리 패턴은 관련된 객체들의 군을 생성하는 인터페이스를 제공하면서 구체적인 클래스의 인스턴스화는 서브클래스에 맡기는 생성 디자인 패턴입니다.
1. 추상 팩토리 패턴 기본 구조
이 패턴은 제품군(Product Family)을 추상화하는 팩토리 인터페이스와 이를 구현한 구체적 팩토리, 그리고 추상 제품과 구체적 제품 클래스로 구성됩니다.
2. C# 예제 코드
// 추상 제품 A
public interface IProductA
{
string GetName();
}
// 추상 제품 B
public interface IProductB
{
string GetName();
}
// 구체적 제품 A1
public class ProductA1 : IProductA
{
public string GetName() => "ProductA1";
}
// 구체적 제품 B1
public class ProductB1 : IProductB
{
public string GetName() => "ProductB1";
}
// 구체적 제품 A2
public class ProductA2 : IProductA
{
public string GetName() => "ProductA2";
}
// 구체적 제품 B2
public class ProductB2 : IProductB
{
public string GetName() => "ProductB2";
}
// 추상 팩토리
public interface IAbstractFactory
{
IProductA CreateProductA();
IProductB CreateProductB();
}
// 구체적 팩토리 1
public class ConcreteFactory1 : IAbstractFactory
{
public IProductA CreateProductA() => new ProductA1();
public IProductB CreateProductB() => new ProductB1();
}
// 구체적 팩토리 2
public class ConcreteFactory2 : IAbstractFactory
{
public IProductA CreateProductA() => new ProductA2();
public IProductB CreateProductB() => new ProductB2();
}
// 클라이언트
public class Client
{
private IProductA productA;
private IProductB productB;
public Client(IAbstractFactory factory)
{
productA = factory.CreateProductA();
productB = factory.CreateProductB();
}
public void Run()
{
Console.WriteLine(productA.GetName());
Console.WriteLine(productB.GetName());
}
}
// 사용 예
class Program
{
static void Main()
{
IAbstractFactory factory1 = new ConcreteFactory1();
Client client1 = new Client(factory1);
client1.Run();
IAbstractFactory factory2 = new ConcreteFactory2();
Client client2 = new Client(factory2);
client2.Run();
}
}
3. 요약
추상 팩토리 패턴을 활용하면 객체 생성 코드를 클라이언트 코드에서 분리하여 제품군을 쉽게 변경하거나 확장할 수 있어 유지보수가 편리합니다.
'C#' 카테고리의 다른 글
| C# Thread.Join과 Thread.Sleep 차이와 활용 (0) | 2026.06.19 |
|---|---|
| C# 대리자 체인 관리와 예외 처리 (0) | 2026.06.19 |
| C# Stopwatch와 PerformanceCounter 비교 분석 (0) | 2026.06.18 |
| C# Custom Binding 구현으로 네트워크 통신 확장 (0) | 2026.06.17 |
| C# 순환 참조 방지 패턴 설계 (0) | 2026.06.17 |