软件开发|编程技术|编程代码|编程入门先学什么—程序设计语言

C++设计模试实现

C++设计模试实现--State

[cpp] view plaincopy

#include

#include

class CContext;

class IState

{

public:

virtual void CurrentState(CContext* Change)=0;

};

class CContext

{

public:

CContext(IState* pState)

:m_state(pState),m_Change(0){}

~CContext(){delete m_state; m_state=NULL;}

void SetChange(int change){m_Change = change;}

int GetChange(){return m_Change;}

void SetState(IState* pState){delete m_state; m_state=pState;}

void ChangeState(){m_state-CurrentState(this);}

private:

IState* m_state;

int m_Change;

};

class CThird : public IState

{

void Third(CContext* Change)

{

printf("third end!\n");

}

virtual void CurrentState(CContext* Change)

{

Third(Change);

}

};

class CSecond : public IState

{

void Second(CContext* Change)

{

if (Change-GetChange()5)

{

static int count = 1;

printf("second [%d]!\n", count++);

}

else

{

Change-SetState(new CThird());

Change-ChangeState();

}

}

virtual void CurrentState(CContext* Change)

{

Second(Change);

}

};

class CFirst : public IState

{

public:

void First(CContext* Change)

{

if ((Change-GetChange())3)

{

static int count = 1;

printf("first [%d]!\n", count++);

}

else

{

Change-SetState(new CSecond());

Change-ChangeState();

}

}

virtual void CurrentState(CContext* Change)

{

First(Change);

}

};

int main(int argc, char* argv)

{

CContext* Change = new CContext(new CFirst());

for (int i=0; i6; ++i)

{

Change-SetChange(i);

Change-ChangeState();

}

delete Change;

Change = NULL;

system("pause");

}