C/C++培训
美国上市C/C++培训机构

400-111-8989

热门课程

C++设计模试实现-State

  • 时间:2015-01-14
  • 发布:达内
  • 来源:达内

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; i<6; ++i)

{

Change->SetChange(i);

Change->ChangeState();

}

delete Change;

Change = NULL;

system("pause");

}

上一篇:C++空类以及没有成员变量的类的大小
下一篇:代理方法关键字Action与Fun的使用

C++设计模试实现-State

代理方法关键字Action与Fun的使用

C++培训:利用C++对象确定性析构的原则来解析单例模式

C语言中蓄水池抽样

选择城市和中心
贵州省

广西省

海南省

台湾