[C++] 纯文本查看 复制代码 #include <iostream>
using namespace std;
#define ID_OPEN 100
#define ID_SAVE 101
#define ID_EXIT 102
class CCmdTarget
{
public:
//要声明为虚函数,形成多态
virtual bool OnCmdMsg(int id)
{
return false;
}
};
class CDocument : public CCmdTarget
{
public:
bool OnCmdMsg(int id) override
{
if (id == ID_SAVE)
{
cout << "CDocument::OnSave()" << endl;
return true;
}
return CCmdTarget::OnCmdMsg(id);
}
};
class CView : public CCmdTarget
{
CDocument* m_pDoc;
public:
CView(CDocument* doc) : m_pDoc(doc) {}
bool OnCmdMsg(int id) override
{
cout << "CView::OnCmdMsg()" << endl;
if (id == ID_OPEN)
{
cout << "CView::OnOpen()" << endl;
return true;
}
// View 自己不处理
// 转给 Document
if (m_pDoc->OnCmdMsg(id))
return true;
return CCmdTarget::OnCmdMsg(id);
}
};
class CWinApp : public CCmdTarget
{
public:
bool OnCmdMsg(int id) override
{
if (id == ID_EXIT)
{
cout << "CWinApp::OnExit()" << endl;
return true;
}
return CCmdTarget::OnCmdMsg(id);
}
};
class CFrameWnd : public CCmdTarget
{
CView* m_pView;
CWinApp* m_pApp;
public:
CFrameWnd(CView* view, CWinApp* app)
: m_pView(view), m_pApp(app) {
}
bool OnCommand(int id)
{
cout << "CFrameWnd::OnCommand()" << endl;
return OnCmdMsg(id);
}
bool OnCmdMsg(int id) override
{
cout << "CFrameWnd::OnCmdMsg()" << endl;
// ① View
if (m_pView->OnCmdMsg(id))
return true;
// ② Frame 自己
if (CCmdTarget::OnCmdMsg(id))
return true;
// ③ App
if (m_pApp->OnCmdMsg(id))
return true;
return false;
}
};
int main()
{
CWinApp app;
CDocument doc;
CView view(&doc);
//这里暂时传入CView,实际中很可能是CView的派生类
CFrameWnd frame(&view, &app);
cout << "---- ID_OPEN ----" << endl;
frame.OnCommand(ID_OPEN);
cout << "\n---- ID_SAVE ----" << endl;
frame.OnCommand(ID_SAVE);
cout << "\n---- ID_EXIT ----" << endl;
frame.OnCommand(ID_EXIT);
cout << "\n---- ID_UNKNOWN ----" << endl;
frame.OnCommand(999);
system("pause");
return 0;
} |