-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommand.cpp
82 lines (71 loc) · 1.07 KB
/
command.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
71
72
73
74
75
76
77
78
79
80
81
#include <vector>
#include <iostream>
using namespace std;
class CommandTarget;
class ICommand
{
public:
virtual void execute( ) = 0;
virtual void setTarget( CommandTarget* p )
{
}
virtual ~ICommand( )
{
}
};
class CommandTarget
{
public:
void action( )
{
cout<<"execute command at target"<<endl;
}
};
class ConcreteCommand: public ICommand
{
public:
virtual void execute( )
{
cout<<"concrete command"<<endl;
m_cmdTgt->action( );
}
void setTarget( CommandTarget* p )
{
m_cmdTgt = p;
}
private:
CommandTarget* m_cmdTgt;
};
class Agent
{
public:
void exec( )
{
vector<ICommand*>::iterator iter = m_cmdLists.begin( );
for( ; iter != m_cmdLists.end( ); iter++ )
{
( *iter)->execute( );
}
}
void addCommand( ICommand* cmd )
{
m_cmdLists.push_back( cmd );
}
private:
vector<ICommand*> m_cmdLists;
};
int main( )
{
Agent newAgent;
CommandTarget ct;
ICommand* cmd = new ConcreteCommand( );
if( cmd == NULL )
{
return -1;
}
cmd->setTarget( &ct );
newAgent.addCommand( cmd );
newAgent.exec( );
delete cmd;
return 0;
}