MFC程序架构设计禁忌

引言

MFC(Microsoft Foundation Classes)是微软提供的一套用于开发Windows桌面应用程序的框架。MFC提供了一系列的类和函数,使得开发者能够更轻松地创建Windows应用程序。

然而,在设计MFC程序的架构时,我们需要遵循一些禁忌,以避免常见的设计错误。本文将讨论一些常见的MFC程序架构设计禁忌,并提供相应的代码示例。

禁忌一:紧密耦合的模块

在MFC程序中,模块是指完成特定功能的代码单元。通常,每个模块都应该是相对独立的,以便于维护和扩展。然而,有时候我们会犯一个错误,就是将多个模块之间紧密耦合在一起。

紧密耦合的模块会导致代码的可维护性和可扩展性降低。当一个模块发生变化时,可能会影响到其他模块的正常运行,从而增加了代码的修改成本。

以下是一个紧密耦合的模块的示例代码:

// ModuleA.h
#pragma once

#include "ModuleB.h"

class ModuleA
{
public:
    ModuleA();
    ~ModuleA();

    void DoSomething();
};

// ModuleA.cpp
#include "ModuleA.h"

ModuleA::ModuleA()
{
}

ModuleA::~ModuleA()
{
}

void ModuleA::DoSomething()
{
    ModuleB b;
    b.DoSomething();
}


// ModuleB.h
#pragma once

#include "ModuleA.h"

class ModuleB
{
public:
    ModuleB();
    ~ModuleB();

    void DoSomething();
};

// ModuleB.cpp
#include "ModuleB.h"

ModuleB::ModuleB()
{
}

ModuleB::~ModuleB()
{
}

void ModuleB::DoSomething()
{
    ModuleA a;
    a.DoSomething();
}

在上述代码中,ModuleAModuleB 互相引用对方的头文件,并在其成员函数中创建对方的实例。这种紧密耦合的设计使得两个模块之间相互依赖,难以独立运行。

应该避免这种紧密耦合的设计,可以通过引入接口或中间层来解耦模块之间的依赖关系。

禁忌二:过于臃肿的View类

在MFC程序中,View类负责显示和处理用户界面。然而,有时候我们会在View类中添加过多的代码,使得View类变得臃肿不堪。

一个过于臃肿的View类不仅难以阅读和维护,还会导致应用程序的性能下降。因此,我们应该避免在View类中添加过多的代码。

以下是一个View类过于臃肿的示例代码:

// MainView.h
#pragma once

#include "afxwin.h"

class MainView : public CView
{
protected:
    DECLARE_DYNCREATE(MainView)

    MainView();
    virtual ~MainView();

    virtual void OnDraw(CDC* pDC);
    virtual BOOL PreCreateWindow(CREATESTRUCT& cs);

    afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
    afx_msg void OnSize(UINT nType, int cx, int cy);
    afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
    afx_msg void OnRButtonDown(UINT nFlags, CPoint point);
    afx_msg void OnMouseMove(UINT nFlags, CPoint point);
    afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
    afx_msg void OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags);
    afx_msg void OnPaint();
    afx_msg void OnTimer(UINT_PTR nIDEvent);
    afx_msg BOOL OnEraseBkgnd(CDC* pDC);

    DECLARE_MESSAGE_MAP()
};

// MainView.cpp
#include "MainView.h"

IMPLEMENT_DYNCREATE(MainView, CView)

MainView::MainView()
{
}

MainView::~MainView()
{
}

void MainView::OnDraw(CDC* pDC)
{
}

BOOL MainView::PreCreateWindow(CREATESTRUCT& cs)
{
}

int MainView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
}

void