[Investor Relations]  |  官方微博

C/C++培训

美国上市公司 · 亿元级外企Java培训企业

  • 全国服务监督电话400-111-8989
  • C++设计模试实现-State

    发布:达内  来源:达内  时间: 2015年01月14日

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

  • 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的使用

网站导航
2001-2016 达内时代科技集团有限公司 版权所有 京ICP证8000853号-56