码迷,mamicode.com
首页 > 其他好文 > 详细

Policy-based design设计模式

时间:2014-10-26 11:44:53      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   io   os   ar   sp   

书在4年前看过,今天重温一下:

一直认为这是最好的设计模式,大牛Andrei Alexandrescu 专门写了书,可见他的重要性

http://en.wikipedia.org/wiki/Policy-based_design

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



对比strategy:An example implementation of the Strategy design pattern in C++

http://r3dux.org/2011/07/an-example-implementation-of-the-strategy-design-pattern-in-c/

Policy-based design设计模式

标签:des   style   blog   http   color   io   os   ar   sp   

原文地址:http://blog.csdn.net/mathgeophysics/article/details/40475489

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!