模式说明:允许一个对象在其内部状态改变时改变它的行为,使对象看起来似乎修改了它的类。
模式图片:
- Context | TLNetTraffic : 包含了不同的状态
- State | TLState : 定义一个状态接口。
- ConcreteState | TL {Red, Yellow, Green} : 定义了不同的状态
¨TLNetTraffic.h¨
1
2
3
4
5
6
7
8
9
| class TLNetTraffic
{
private:
TLState* _state;
public:
TLNetTraffic();
void setState ( TLState* state );
void Handle();
}; | |
¨TLNetTraffic.cpp¨
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| TLNetTraffic::TLNetTraffic()
{
_state = new TLRed(this);
}
void TLNetTraffic::setState ( TLState* state )
{
_state = state;
}
void TLNetTraffic::Handle ()
{
_state->Handle();
} | |
TLState.h¨
1
2
3
4
5
| class TLState
{
public:
virtual void Handle() = 0;
}; | |
...我们随意定义了 三种状态,当然可以定义的更多
¨TLRed.h¨
1
2
3
4
5
6
7
8
9
| class TLRed: public TLState
{
private:
TLNetTraffic* _context;
public:
TLRed(TLNetTraffic* context);
void Handle();
}; | |
¨TLRed.cpp¨
1
2
3
4
5
6
7
| TLRed::TLRed(TLNetTraffic* context): _context(context) {};
void TLRed::Handle()
{
printf("Red Light\n");
_context->setState( new TLGreen(_context) );
} | |
¨TLGreen.h¨
1
2
3
4
5
6
7
8
9
| class TLGreen: public TLState
{
private:
TLNetTraffic* _context;
public:
TLGreen(TLNetTraffic* context);
void Handle();
}; | |
¨TLGreen.cpp¨
1
2
3
4
5
6
7
| TLGreen::TLGreen(TLNetTraffic* context): _context(context) {};
void TLGreen::Handle()
{
printf("Green Light\n");
_context->setState( new TLYellow(_context) );
} | |
¨TLYellow.h¨
1
2
3
4
5
6
7
8
9
| class TLYellow: public TLState
{
private:
TLNetTraffic* _context;
public:
TLYellow(TLNetTraffic* context);
void Handle();
}; | |
¨TLYellow.cpp¨
1
2
3
4
5
6
7
| TLYellow::TLYellow(TLNetTraffic* context): _context(context) {};
void TLYellow::Handle()
{
printf("Yellow Light\n");
_context->setState( new TLRed(_context) );
} | |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| int main (int argc, char* argv[])
{
TLNetTraffic netTraffic;
int count = 0, i=0;
int seconds;
while(1)
{
if (i%3==0)
printf("---------\nSession %d\n---------\n", ((i+1)/3)+1 );
if (count == 0) seconds =6, count = 1;
else if (count == 1) seconds = 4, count = 2;
else if (count == 2) seconds = 5, count = 0;
sleep( (clock_t)seconds * CLOCKS_PER_SEC );
netTraffic.Handle();
i++;
}
return 0;
} |
|
原文:
http://www.cplusplus.com/articles/zAqpX9L8/