zoukankan      html  css  js  c++  java
  • Policy-based design设计模式

    书在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!"
    }

    补充:

    Templates as Interfaces
    The C++ idiom to express the Talkative interface discussed in Venners's article would look something like this:
    
    template <class T>
    class Talkative 
    {
      T const & t;
    public:
      Talkative(T const & obj) : t(obj) { }
      void talk() const { t.talk(); }
    };



    对照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/

  • 相关阅读:
    Jenkins持续集成
    爬豆瓣保存到sqlite3
    爬豆瓣保存到Excel
    sqlite3数据库的增删查改
    用pandas和matplotlib对用户消费行为分析
    TCP请求
    fastjson
    断言
    将结果写入文件
    加解密
  • 原文地址:https://www.cnblogs.com/mthoutai/p/6871667.html
Copyright © 2011-2022 走看看