-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathstate.cpp
70 lines (53 loc) · 1.11 KB
/
state.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream>
#include <boost/shared_ptr.hpp>
using std::cout;
using std::endl;
using boost::shared_ptr;
class person;
class state{
public:
virtual void execute(person*) = 0;
virtual ~state(){};
private:
};
class person{
public:
explicit person(int tired):_tired(tired){};
void update(){this->_state->execute(this);}
void set_state(shared_ptr<state> state){this->_state = state;};
int _tired;
private:
shared_ptr<state> _state;
};
class workstate:public state{
public:
void execute(person* p);
};
class reststate:public state{
public:
void execute(person* p);
};
void workstate::execute(person* p){
if (p->_tired > 15){
p->set_state(shared_ptr<state>(new reststate()));
} else{
p->_tired += 1;
cout<<"hey i am working"<<endl;
}
}
void reststate::execute(person* p){
if (p->_tired < 5){
p->set_state(shared_ptr<state>(new workstate()));
} else{
p->_tired -= 1;
cout<<"hey i am resting"<<endl;
}
}
int main(int argc, char const *argv[])
{
auto p = shared_ptr<person>(new person(0));
p->set_state(shared_ptr<state>(new workstate()));
for(int i = 0; i != 100; ++i){
p->update();
}
}