题目要求是自己开脑洞想一个状态模式的例子,实现之。
例子详见后文。
状态模式简介:
http://www.cnblogs.com/wangjq/archive/2012/07/16/2593485.html
State.h
#pragma once
#include "Person.h"
class Person;
class State
{
public:
State() = default;
~State() = default;
virtual void study(Person *per) = 0;
virtual void play(Person *per) = 0;
virtual void eat(Person *per) = 0;
virtual void exam(Person *per) = 0;
void sleep(Person *per);
};
State.cpp
#include "State.h"
#include "Person.h"
#include <iostream>
using namespace std;
void State::sleep(Person *per)
{
cout << "Sound Sleep ~" << endl;
cout << "a new day is coming ~" << endl;
per -> setstate(per -> getNewState());
return ;
}
Exciting.h
#pragma once
#include "State.h"
class Exciting : public State
{
public:
Exciting() = default;
~Exciting() = default;
virtual void study(Person *per) override;
virtual void play(Person *per) override;
virtual void eat(Person *per) override;
virtual void exam(Person *per) override;
};
Exciting.cpp
#include <iostream>
#include "Exciting.h"
#include "Person.h"
#include "Happy.h"
#include "Sad.h"
#include "Soso.h"
using namespace std;
void Exciting::study(Person *per)
{
cout << "Excited! Study!" << endl;
cout << "Gain lots of knowledge! You're content with yourself~" << endl;
per -> setstate(new Happy);
cout << "Get into Happy Mode ~" << endl;
return ;
}
void Exciting::play(Person *per)
{
cout << "Excited! Play!" << endl;
cout << "You win a lot!" << endl;
cout << "Still Exciting!" << endl;
}
void Exciting::eat(Person *per)
{
cout << "Excited! Eat!" << endl;
cout << "You eat too much!" << endl;
per -> setstate(new Soso);
cout << "Get into Soso Mode" << endl;
}
void