首页 > 代码库 > 【设计模式】状态模式

【设计模式】状态模式

 

这一篇只有代码

 

// State.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <iostream>using namespace std;//强制声明class CMe;//状态抽象基类class CState{public:     CState();    virtual ~CState();     virtual void Show(CMe* pMe) = 0;   };CState::CState(){}CState::~CState(){}//单身状态类class CSingle : public CState{public:    CSingle();    virtual ~CSingle();    virtual void Show(CMe* pMe);};CSingle::CSingle(){}CSingle::~CSingle(){}void CSingle::Show(CMe* pMe){    cout << endl << "哥哥是单身狗啊单身狗!!!" << endl;    }//有女朋友状态类class CWithGirl : public CState{public:    CWithGirl();    virtual ~CWithGirl();    virtual void Show(CMe* pMe) ;};CWithGirl::CWithGirl(){}CWithGirl::~CWithGirl(){}void CWithGirl::Show(CMe* pMe){     cout << endl << "哥哥有女朋友了啊好幸福!!!" << endl;}//我 类class CMe{public:    CMe();    virtual ~CMe();    void SetState(CState* pState);  //设置状态    void ShowMsg();                    //显示此状态的信息protected:    CState* m_ptrState; };CMe::CMe() : m_ptrState(NULL){}CMe::~CMe(){}void CMe::SetState(CState* pState){    m_ptrState = pState;}void CMe::ShowMsg(){    m_ptrState->Show(this);}int _tmain(int argc, _TCHAR* argv[]){     CMe me1;    me1.SetState(new CSingle());    me1.ShowMsg();    cout << endl << endl;    me1.SetState(new CWithGirl());    me1.ShowMsg();    cout << endl << endl;    return 0;}

 

 

执行结果

 

 

具体解释见下一篇