Policy-based design设计模式

本文重新探讨了Policy-based design设计模式,该模式被Andrei Alexandrescu推崇,并著书详细阐述其重要性。通过链接提供的资源,读者可以了解Policy-based design与Strategy设计模式的对比,以及C++中Strategy模式的实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

书在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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值