[c#] 데코레이터 패턴과 컴포지트 패턴의 관계

데코레이터 패턴과 컴포지트 패턴은 모두 객체 지향 디자인 패턴 중 하나인데, 이 둘 사이에는 어떤 관계가 있을까요? 또한, 이 두 패턴의 핵심 차이점은 무엇일까요? 이 글에서는 이러한 의문을 해결하고 데코레이터 패턴과 컴포지트 패턴의 기본 개념을 설명하겠습니다.

데코레이터 패턴

데코레이터 패턴은 객체의 동작을 동적으로 변경하고 확장하기 위한 패턴으로, 객체에 대한 기능을 추가할 때 상속을 사용하는 대신, 구성을 통해 기능을 확장하는 방식을 제공합니다. 데코레이터 패턴은 기존의 객체에 새로운 기능을 추가하거나 수정할 수 있게 해줍니다.

예를 들어, 새로운 기능을 추가하기 위해 기존 클래스를 변경하지 않고, 데코레이터 클래스를 사용하여 기능을 덧붙일 수 있습니다. 이는 기존 코드를 변경하지 않고도 새로운 기능을 추가할 수 있게 해주어 유연성과 확장성을 제공합니다.

public interface IComponent
{
    void Operation();
}

public class ConcreteComponent : IComponent
{
    public void Operation()
    {
        Console.WriteLine("Executing operation in ConcreteComponent");
    }
}

public abstract class Decorator : IComponent
{
    protected IComponent component;

    public Decorator(IComponent component)
    {
        this.component = component;
    }

    public virtual void Operation()
    {
        component.Operation();
    }
}

public class ConcreteDecorator : Decorator
{
    public ConcreteDecorator(IComponent component) : base(component) { }

    public override void Operation()
    {
        base.Operation();
        // Additional operation
        Console.WriteLine("Executing additional operation in ConcreteDecorator");
    }
}

// Usage
IComponent component = new ConcreteComponent();
component = new ConcreteDecorator(component);
component.Operation();

컴포지트 패턴

컴포지트 패턴은 객체들을 트리 구조로 구성하여, 단일 객체와 복합 객체를 동일하게 취급할 수 있도록 하는 패턴입니다. 즉, 개별 객체와 객체들의 합으로 구성된 복합 객체를 동일하게 다룰 수 있는 통일된 방법을 제공합니다.

컴포지트 패턴은 객체들 간에 부모-자식 관계를 형성하여, 클라이언트는 개별 객체와 복합 객체를 동일하게 다룰 수 있습니다.

public interface IComponent
{
    void Operation();
}

public class Leaf : IComponent
{
    public void Operation()
    {
        Console.WriteLine("Executing operation in Leaf");
    }
}

public class Composite : IComponent
{
    private List<IComponent> children = new List<IComponent>();

    public void Add(IComponent component)
    {
        children.Add(component);
    }

    public void Remove(IComponent component)
    {
        children.Remove(component);
    }

    public void Operation()
    {
        foreach (var child in children)
        {
            child.Operation();
        }
    }
}

// Usage
IComponent leaf = new Leaf();
IComponent composite = new Composite();
composite.Add(leaf);
composite.Operation();

데코레이터 패턴과 컴포지트 패턴의 관계

데코레이터 패턴과 컴포지트 패턴은 둘 다 구성 요소를 활용하여 객체의 기능을 확장하거나 조합하는 방법을 제공합니다. 그러나 데코레이터 패턴은 개별 객체에 새로운 기능을 추가하거나 수정하는 데 사용되는 반면, 컴포지트 패턴은 개별 객체와 복합 객체를 동일하게 취급하여 사용하는데 주로 사용됩니다.

따라서, 두 패턴은 각각 객체의 동작을 확장하고 조합하는데 활용되지만, 그 목적과 활용 방식에서 차이가 있습니다.

감사합니다.