iT邦幫忙

2023 iThome 鐵人賽

DAY 16
0
自我挑戰組

設計模式系列 第 16

Day16 - 策略模式(Strategy pattern)

  • 分享至 

  • xImage
  •  

介紹
策略模式將同系列的算法封裝起來,讓使用者可在runtime時替換這些算法。

C++範例

#include <iostream>

class StrategyInterface
{
public:
    virtual void Execute() const = 0;
};

class ConcreteStrategyA : public StrategyInterface
{
public:
    void Execute() const override
    {
        std::cout << "Called ConcreteStrategyA execute method" << std::endl;
    }
};

class ConcreteStrategyB : public StrategyInterface
{
public:
    void Execute() const override
    {
        std::cout << "Called ConcreteStrategyB execute method" << std::endl;
    }
};

class Context
{
public:
    explicit Context(StrategyInterface *strategy) : m_strategy(strategy)
    {
    }

    void Setstrategy(StrategyInterface *strategy)
    {
        m_strategy = strategy;
    }

    void Execute() const
    {
        m_strategy->Execute();
    }

private:
    StrategyInterface *m_strategy;
};

int main(int argc, char *argv[])
{
    ConcreteStrategyA concreteStrategyA;
    ConcreteStrategyB concreteStrategyB;

    // 設定為策略A
    Context context(&concreteStrategyA);
    // 執行策略A
    context.Execute();

    // 設定為策略B
    context.Setstrategy(&concreteStrategyB);
    // 執行策略B
    context.Execute();

    return 0;
}

Output:

Called ConcreteStrategyA execute method
Called ConcreteStrategyB execute method

Ref:
https://en.wikibooks.org/wiki/C%2B%2B_Programming/Code/Design_Patterns#Strategy


上一篇
Day15 - 責任鏈模式(Chain of responsibility pattern)
下一篇
Day17 - 狀態模式(State pattern)
系列文
設計模式30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言