프로그래밍/GoF

[구조 패턴] - 데코레이터(Decorator)

MAKGA 2022. 1. 11. 21:32
320x100

구조

#pragma once

#include <iostream>

class IComponent
{
public:
    virtual void Operate() = 0;
};

class Component : public IComponent
{
public:
    void Operate() override
    {
        std::cout << "Operating Component" << std::endl;
    }
};

class Decorator : public IComponent
{
public:
    Decorator(IComponent* component)
    {
        component_ = component;
    }

    virtual void Operate() override = 0;

protected:
    IComponent* component_;
};

class DecoratorA : public Decorator
{
public:
    DecoratorA(IComponent* component)
        : Decorator(component)
    {
    }

    void Operate() override
    {
        component_->Operate();

        std::cout << "Powered by DecoratorA" << std::endl;
    }
};

class DecoratorB : public Decorator
{
public:
    DecoratorB(IComponent* component)
        : Decorator(component)
    {
    }

    void Operate() override
    {
        component_->Operate();

        std::cout << "Powered by DecoratorB" << std::endl;
    }
};

 

사용

int main()
{
    IComponent* decoratorA = new DecoratorA(new Component());
    IComponent* decoratorB = new DecoratorB(decoratorA);

    decoratorA->Operate();
    decoratorB->Operate();

    return 0;
}

 

데코레이터 객체는 객체와 동일한 인터페이스를 클라이언트에게 제공하기에 데코레이터 객체 자체를 해당 객체처럼 사용할수도 있고 데코레이터 객체가 인터페이스가 같은 데코레이터 객체를 참조하여 기능의 확장을 중첩적으로 수행할 수도 있다. 클라이언트에게 객체와 동일한 인터페이스를 제공한다는 점에 있어 프록시 (Proxy) 패턴과 유사하나, 데코레이터 패턴은 객체의 중개가 아닌 기능 확장이 목적이라는 것이 프록시 패턴과의 핵심적인 차이이다.

320x100