Policy-based Design - Simple Example

Simple Example

Presented below is a simple (contrived) example of a C++ hello world program, where the text to be printed and the method of printing it are decomposed using policies.

#include #include template 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 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 { /* Example 1 */ typedef HelloWorld HelloWorldEnglish; HelloWorldEnglish hello_world; hello_world.run; // prints "Hello, World!" /* Example 2 * Does the same, but uses another language policy */ typedef HelloWorld HelloWorldGerman; HelloWorldGerman hello_world2; hello_world2.run; // prints "Hallo Welt!" }

You could easily write another OutputPolicy by adding a new class with the member function print and take that as the new OutputPolicy.

Read more about this topic:  Policy-based Design

Famous quotes containing the word simple:

    “How simple a thing it seems to me that to know ourselves as we are, we must know our mothers’ names.”
    —Alice Walker (b. 1944)

    “Historians desiring to write the actions of men, ought to set down the simple truth, and not say anything for love or hatred; also to choose such an opportunity for writing as it may be lawful to think what they will, and write what they think, which is a rare happiness of the time.”
    —Sir Walter Raleigh (1552–1618)