-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathState.h
87 lines (78 loc) · 1.44 KB
/
State.h
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#pragma once
#include <string>
#include <istream>
using namespace std;
class TraficLight;
class GreenState;
class RedState;
class TraficLight
{
public:
friend class RedState;
friend class GreenState;
class AbstractState
{
public:
virtual bool allow()const = 0;
virtual void getNext(TraficLight& state) = 0;
};
class RedState : public AbstractState
{
public:
bool allow()const { return false; }
void getNext(TraficLight& obj)
{
obj.mCurrentState = new GreenState;
delete this;
};
};
class GreenState : public AbstractState
{
public:
bool allow()const { return true; }
void getNext(TraficLight& obj)
{
obj.mCurrentState = new RedState;
delete this;
}
};
TraficLight() = default;
TraficLight(string name) : mName(name)
{
mCurrentState = new RedState;
}
TraficLight(const TraficLight& copy):
mName(copy.mName)
{
mCurrentState = new RedState;
if (copy.allow())
{
update();
}
}
~TraficLight() { delete mCurrentState; }
bool allow()const
{
return mCurrentState->allow();
}
void update()
{
mCurrentState->getNext(*this);
}
string name()const { return mName; }
TraficLight operator=(const TraficLight& copy)
{
delete mCurrentState;
mCurrentState = new RedState;
if (copy.allow())
{
update();
}
return *this;
}
private:
string mName;
AbstractState* mCurrentState;
};
//inline GreenState* getGreen() { return new GreenState; }
//inline RedState* getRed() { return new RedState; }