단위전략 기반 디자인

단위전략이라고 불리는 C++의 이디엄에서 비롯된 컴퓨터 프로그래밍 패러다임이다.

단위전략 기반 디자인(Policy-based design) 혹은 단위전략 기반 클래스 디자인(policy-based class design), 단위전략 기반 프로그래밍(policy-based programming) 은 단위전략이라고 불리는 C++의 이디엄에서 비롯된 컴퓨터 프로그래밍 패러다임이다. 이는 전략 패턴을 컴파일 타임에 적용하는 것이며, C++의 템플릿 메타프로그래밍과 연관이 있다. 단위전략 기반 디자인은 Andrei Alexandrescu의 저서인 Modern C++ Design을 통해서 대중에 알려졌다.

단위전략 기반 디자인은 이론적으로 다른 프로그래밍 언어에도 적용할 수 있으나 언어의 기능에 의존적이기 때문에 C++을 중심으로 논의가 전개되고 있다. C++의 경우에도 템플릿을 지원하는 컴파일러가 필요하다.

간단한 예 편집

아래의 예는 C++의 Hello world 프로그램을 출력되는 언어와 출력되는 스트림을 선택할 수 있도록 단위전략 기반 디자인을 이용하여 수정한 것이다.

#include <iostream>
#include <string>

template <typename OutputPolicy, typename LanguagePolicy>
class HelloWorld : private OutputPolicy, private LanguagePolicy
{
    using OutputPolicy::print;
    using LanguagePolicy::message;

public:
    // Behaviour method
    void run() const
    {
        // Two policy methods
        print(message());
    }
};

class OutputPolicyWriteToCout
{
protected:
    template<typename MessageType>
    void print(MessageType const &message) const
    {
        std::cout << message << std::endl;
    }
};

class LanguagePolicyEnglish
{
protected:
    std::string message() const
    {
        return "Hello, World!";
    }
};

class LanguagePolicyGerman
{
protected:
    std::string message() const
    {
        return "Hallo Welt!";
    }
};

int main()
{
    /* 예 1 */
    typedef HelloWorld<OutputPolicyWriteToCout, LanguagePolicyEnglish> HelloWorldEnglish;

    HelloWorldEnglish hello_world;
    hello_world.run(); // prints "Hello, World!"

    /* 예 2
     *위와 같지만, 다른 언어를 출력하도록 하였다  */
    typedef HelloWorld<OutputPolicyWriteToCout, LanguagePolicyGerman> HelloWorldGerman;

    HelloWorldGerman hello_world2;
    hello_world2.run(); // prints "Hallo Welt!"
}

멤버 함수로 print를 가지는 또 다른 OutputPolicy에 대한 클래스를 작성하는 것으로 새로운 OutputPolicy를 정의할 수 있다.

외부 링크 편집