Skip to content

Commit 8e39f35

Browse files
authored
command pattern added
1 parent e16c3ee commit 8e39f35

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

CommandPattern/main.cpp

+78
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
#include <iostream>
2+
using namespace std;
3+
4+
class RecieverLight {
5+
public:
6+
void TurnLightOn() {
7+
cout << "Turning Light on" << endl;
8+
}
9+
void TurnLightOff()
10+
{
11+
cout << "Turning Light off" << endl;
12+
}
13+
};
14+
15+
class Command {
16+
public:
17+
virtual ~Command() { }
18+
virtual void Excute() = 0;
19+
};
20+
21+
class TurnOnCommand :public Command {
22+
public:
23+
TurnOnCommand(RecieverLight *rev) {
24+
_rev = rev;
25+
}
26+
27+
void Excute() {
28+
_rev->TurnLightOn();
29+
}
30+
private:
31+
RecieverLight *_rev;
32+
};
33+
34+
class TurnOffCommand :public Command {
35+
public:
36+
TurnOffCommand(RecieverLight *rev) {
37+
_rev = rev;
38+
}
39+
40+
void Excute() {
41+
_rev->TurnLightOff();
42+
}
43+
private:
44+
RecieverLight *_rev;
45+
};
46+
47+
class Invoker
48+
{
49+
public:
50+
void setCommand(Command* cmd)
51+
{
52+
_cmd = cmd;
53+
}
54+
void Invoke() {
55+
_cmd->Excute();
56+
}
57+
58+
private:
59+
Command *_cmd;
60+
};
61+
62+
int main() {
63+
RecieverLight *rev = new RecieverLight();
64+
Command *lightOn = new TurnOnCommand(rev);
65+
Command *lightOff = new TurnOffCommand(rev);
66+
Invoker *inv = new Invoker();
67+
inv->setCommand(lightOn);
68+
inv->Invoke();
69+
inv->setCommand(lightOff);
70+
inv->Invoke();
71+
72+
delete rev;
73+
delete lightOn;
74+
delete inv;
75+
delete lightOff;
76+
77+
return 0;
78+
}

0 commit comments

Comments
 (0)