模板方法模式.cpp
#include <iostream>
#include <memory>
using namespace std;
namespace ns1
{
class Warrior
{
int m_life;
int m_magic;
int m_attack;
public:
Warrior(int life, int magic, int attack) : m_life(life), m_magic(magic), m_attack(attack) {}
public:
void JN_Burn()
{
m_life -= 300;
cout << "Lose 500 HP points for each enemy" << endl;
cout << "The protagonist loses 300 HP" << endl;
cout << "Play the special effect of the \"burning\" skill to the players" << endl;
}
};
}
namespace ns2
{
class Fighter
{
protected:
int m_life;
int m_magic;
int m_attack;
public:
Fighter(int life, int magic, int attack) : m_life(life), m_magic(magic), m_attack(attack) {}
virtual ~Fighter() {}
void JN_Burn()
{
if (canUseJN())
{
effect_enemy();
effect_self();
play_effect();
}
}
private:
virtual bool canUseJN() const = 0;
private:
virtual void effect_enemy() const {}
virtual void effect_self() {}
private:
void play_effect() const { cout << "Play the special effect of the \"burning\" skill to the players" << endl; }
};
class F_Warrior : public Fighter
{
public:
F_Warrior(int life, int magic, int attack) : Fighter(life, magic, attack) {}
private:
bool canUseJN() const override { return m_life >= 300; }
private:
void effect_enemy() const override
{
cout << "Lose 500 HP points for each enemy" << endl;
}
void effect_self() override
{
cout << "The protagonist loses 300 HP" << endl;
m_life -= 300;
}
};
class F_Mage : public Fighter
{
public:
F_Mage(int life, int magic, int attack) : Fighter(life, magic, attack) {}
private:
bool canUseJN() const override { return m_magic >= 100; }
private:
void effect_enemy() const override
{
cout << "Lose 650 HP points for each enemy" << endl;
}
void effect_self() override
{
cout << "The protagonist loses 100 MV" << endl;
m_magic -= 100;
}
};
}
int main()
{
#if 0
using namespace ns1;
shared_ptr<Warrior> mroleobj(new Warrior(1000, 0, 200));
mroleobj->JN_Burn();
#endif
#if 1
using namespace ns2;
shared_ptr<Fighter> fighter(new F_Warrior(1000, 0, 200));
fighter->JN_Burn();
cout << "-------------------------" << endl;
fighter.reset(new F_Mage(800, 200, 300));
fighter->JN_Burn();
#endif
cout << "Over!\n";
return 0;
}