[c#] 메서드의 템플릿 메서드 패턴

템플릿 메서드 패턴은 객체 지향 프로그래밍에서 사용되는 디자인 패턴 중 하나로, 알고리즘의 구조를 정의하고 서브클래스에서 하나 이상의 단계를 구현할 수 있게 하는 패턴입니다. 이 패턴은 C#에서도 매우 유용하게 쓰일 수 있습니다.

패턴 개요

템플릿 메서드 패턴은 특정 알고리즘의 기본 구조를 정의하고, 알고리즘이 구체적으로 구현되는 세부 단계는 하위 클래스로 위임하는 방식으로 동작합니다. 즉, 특정 작업을 처리하는 방법의 일부를 기본 클래스에 구현하고, 나머지는 하위 클래스에 구현할 수 있게 합니다.

C#에서의 예제

다음은 C#에서 템플릿 메서드 패턴을 구현한 간단한 예제입니다. 이 예제는 다음과 같은 과정을 수행하는 가상의 주문 처리 시스템을 나타냅니다.

using System;

// Abstract class
abstract class OrderProcessTemplate
{
    public bool IsGift;

    // 템플릿 메서드
    public void ProcessOrder(bool isGift)
    {
        this.IsGift = isGift;
        DoSelectProduct();
        if (IsGift)
            DoGiftWrapping();
        DoPayment();
        DoDelivery();
    }

    protected abstract void DoSelectProduct();
    protected abstract void DoPayment();

    // Hook 메서드
    protected virtual void DoGiftWrapping()
    {
        Console.WriteLine("Gift wrapping done.");
    }

    protected virtual void DoDelivery()
    {
        Console.WriteLine("Delivery done.");
    }
}

// Concrete class
class OnlineOrderProcess : OrderProcessTemplate
{
    protected override void DoSelectProduct()
    {
        Console.WriteLine("Product selected from online store.");
    }

    protected override void DoPayment()
    {
        Console.WriteLine("Payment done through online payment system.");
    }
}

class StoreOrderProcess : OrderProcessTemplate
{
    protected override void DoSelectProduct()
    {
        Console.WriteLine("Product selected from store inventory.");
    }

    protected override void DoPayment()
    {
        Console.WriteLine("Payment done at store counter.");
    }

    protected override void DoGiftWrapping()
    {
        Console.WriteLine("Gift wrapping not available for in-store orders.");
    }
}

이 예제에서 OrderProcessTemplate 클래스는 템플릿 메서드를 정의하고, 하위 클래스에서 각각의 단계를 구체화하도록 합니다. OnlineOrderProcessStoreOrderProcess 클래스는 각각의 단계를 구현하는 구체 클래스입니다.

마치며

템플릿 메서드 패턴은 C#에서 코드의 재사용성과 유연성을 높일 수 있는 강력한 도구입니다. 이 패턴을 사용하면 특정 작업의 기본 구조는 유지하면서, 다양한 변형 방식으로 확장할 수 있게 됩니다.

참조: Microsoft Docs - Template Method Design Pattern