⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 fsm.cpp

📁 MARS加密解密
💻 CPP
字号:
// FSM.cpp: implementation of the CFSM class.
//
//	本程序是《疯狂的火星虫—面向对象状态机实践指南》的演示程序
//
//	版权所有 (C) 2004 王咏武
//	http://www.contextfree.net/wangyw/
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "FSM.h"

CFSM::~CFSM()
{
    // 释放所有的状态对象
    vector<CState *>::iterator it;
    for (it = m_States.begin(); it < m_States.end(); it ++)
        if (*it)
            delete *it;
}

void CFSM::ActiveDefaultState()
{
    ASSERT(! m_States.empty());
    if (! m_States.empty())
    {
        // 激活根状态
        (* m_States.begin())->Active(this, * m_States.begin());
        // 激活根状态到缺省叶子状态
        (* m_States.begin())->ActiveDefaultChild(this);
    }
}

void CFSM::TransitTo(const char * lpName)
{
    CState * pState = GetState(lpName);
    // 找不到状态,说明用户提供的状态名不对
    ASSERT(pState);

    if (pState)
    {
        CState * pCommonAncestor = pState;
        while (! pCommonAncestor->IsActive())
        pCommonAncestor = pCommonAncestor->GetParent();
        
        // 停止所有的活动状态
        pCommonAncestor->Deactive(this);
        // 激活根状态到目的状态
        pState->Active(this, pCommonAncestor);
        // 激活目的状态到缺省叶子状态
        pState->ActiveDefaultChild(this);
    }
}

void CFSM::SendEvent(WORD wEvent, WORD wParam, DWORD lParam)
{
    ASSERT(! m_States.empty());
    if (! m_States.empty())
    {
        // 发送事件给根状态
        (* m_States.begin())->SendEvent(this, wEvent, wParam, lParam);
    }
}

const char * CFSM::GetActiveLeaf()
{
    ASSERT(! m_States.empty());
    if (! m_States.empty())
    {
        return (* m_States.begin())->GetActiveLeaf();
    }
    return NULL;
}

CState * CFSM::GetState(const char * lpName)
{
    CState * pState = NULL;
    // 根据名字得到状态的指针
    for (int i = 0; i < m_States.size(); i++)
        if (! strcmp(m_States[i]->GetName(), lpName))
        {
            pState = m_States[i];
            break;
        }
    return pState;        
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -