iT邦幫忙

2023 iThome 鐵人賽

DAY 19
0
自我挑戰組

設計模式系列 第 19

Day19 - 解釋器模式(Interpret pattern)

  • 分享至 

  • xImage
  •  

介紹
解釋器模式使用已定義語言來解釋傳入的句子。

C++範例

#include <iostream>
#include <vector>
#include <string>

class Player
{
public:
    Player() {}
    ~Player() {}

    void Right()
    {
        std::cout << "Player turns right" << std::endl;
    }

    void Jump()
    {
        std::cout << "Player jumps" << std::endl;
    }
};

class Expression
{
public:
    Expression()
    {
        m_Player = new Player();
    }

    virtual ~Expression()
    {
        delete m_Player;
    }

    virtual void Interpret() = 0;

protected:
    Player *m_Player;
};

class PlayerTurnsRight : public Expression
{
public:
    virtual void Interpret()
    {
        m_Player->Right();
    }
};

class PlayerJumps : public Expression
{
public:
    virtual void Interpret()
    {
        m_Player->Jump();
    }
};

int main()
{
    // 解釋器解釋字串到對應的Player行為
    std::vector<std::string> exps{"right", "jump"};
    Expression *expression;
    for (const std::string &exp : exps)
    {
        if (exp == "right")
        {
            expression = new PlayerTurnsRight();
            expression->Interpret();
            delete expression;
        }
        else if (exp == "jump")
        {
            expression = new PlayerJumps();
            expression->Interpret();
            delete expression;
        }
    }

    return 0;
}

Output:

Player turns right
Player jumps

上一篇
Day18 - 命令模式(Command pattern)
下一篇
Day20 - 迭代器模式(Iterator pattern)
系列文
設計模式30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言