介紹
解釋器模式使用已定義語言來解釋傳入的句子。
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