-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathold_school_fsm.cpp
More file actions
63 lines (51 loc) · 1.33 KB
/
old_school_fsm.cpp
File metadata and controls
63 lines (51 loc) · 1.33 KB
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
#include <iostream>
#include <string>
using namespace std;
/**
* This is a old school implementation for state machines, relying on
* fragile constructs:
* - states have functions to be called.
* - states do the transition themselves.
* - usage of delete this.
*/
class LightSwitch;
struct State {
virtual ~State(){};
virtual void on(LightSwitch *) { cout << "Light is already on\n"; }
virtual void off(LightSwitch *) { cout << "Light is already off\n"; }
};
struct OnState : State {
OnState() { cout << "Light turned on\n"; }
// Only off() is overriden
void off(LightSwitch *ls) override;
};
struct OffState : State {
OffState() { cout << "Light turned off\n"; }
// Only on() is overriden
void on(LightSwitch *ls) override;
};
class LightSwitch {
State *state;
public:
explicit LightSwitch() { state = new OffState(); }
void set_state(State *state) { this->state = state; }
void on() { state->on(this); }
void off() { state->off(this); }
};
void OnState::off(LightSwitch *ls) {
cout << "Switching light off...\n";
ls->set_state(new OffState());
delete this; // delete self!: red flag!
}
void OffState::on(LightSwitch *ls) {
cout << "Switching light on...\n";
ls->set_state(new OnState());
delete this; // delete self!
}
int main() {
LightSwitch ls;
ls.on();
ls.off();
ls.off();
return 0;
}