# 项目架构知识体系

## Qt项目标准架构

### 目录结构最佳实践
```
BattlefieldExplorationSystem/
├── src/                    # 源代码目录
│   ├── core/              # 核心业务逻辑
│   │   ├── database/      # 数据库相关
│   │   ├── network/       # 网络通信
│   │   └── algorithms/    # 核心算法
│   ├── ui/                # 用户界面
│   │   ├── main/          # 主窗口
│   │   ├── dialogs/       # 对话框
│   │   └── components/    # UI组件
│   ├── utils/             # 工具类
│   └── main.cpp           # 程序入口
├── include/               # 头文件目录
│   ├── core/              # 核心头文件
│   ├── ui/                # UI头文件
│   └── utils/             # 工具头文件
├── resources/             # 资源文件
│   ├── images/            # 图片资源
│   ├── qml/               # QML文件
│   ├── styles/            # 样式文件
│   └── translations/      # 翻译文件
├── tests/                 # 测试代码
│   ├── unit/              # 单元测试
│   ├── integration/       # 集成测试
│   └── ui/                # UI测试
├── docs/                  # 文档目录
│   ├── api/               # API文档
│   ├── design/            # 设计文档
│   └── user/              # 用户文档
├── build/                 # 构建输出
├── CMakeLists.txt         # CMake配置
└── README.md              # 项目说明
```

### 模块化架构设计
```cpp
// 核心模块接口定义
namespace Core {
    class IDatabase {
    public:
        virtual ~IDatabase() = default;
        virtual bool connect(const QString& connectionString) = 0;
        virtual bool execute(const QString& query) = 0;
        virtual QVariant getValue(const QString& key) = 0;
    };
    
    class INetworkManager {
    public:
        virtual ~INetworkManager() = default;
        virtual void sendRequest(const QNetworkRequest& request) = 0;
        virtual void setProxy(const QNetworkProxy& proxy) = 0;
    };
}

// UI模块接口定义
namespace UI {
    class IMainWindow {
    public:
        virtual ~IMainWindow() = default;
        virtual void showMessage(const QString& message) = 0;
        virtual void updateStatus(const QString& status) = 0;
    };
    
    class IDevicePanel {
    public:
        virtual ~IDevicePanel() = default;
        virtual void addDevice(const DeviceInfo& info) = 0;
        virtual void removeDevice(const QString& deviceId) = 0;
        virtual void updateDevice(const DeviceInfo& info) = 0;
    };
}
```

## 分层架构模式

### 三层架构实现
```cpp
// 表示层 (Presentation Layer)
class MainWindow : public QMainWindow, public UI::IMainWindow {
    Q_OBJECT
public:
    explicit MainWindow(std::shared_ptr<BusinessLogic> logic, 
                       QWidget *parent = nullptr);
    
    void showMessage(const QString& message) override;
    void updateStatus(const QString& status) override;
    
private slots:
    void onDeviceAdded(const DeviceInfo& info);
    void onDeviceRemoved(const QString& deviceId);
    
private:
    std::shared_ptr<BusinessLogic> m_businessLogic;
    Ui::MainWindow *ui;
};

// 业务逻辑层 (Business Logic Layer)
class BusinessLogic : public QObject {
    Q_OBJECT
public:
    explicit BusinessLogic(std::shared_ptr<Core::IDatabase> database,
                          std::shared_ptr<Core::INetworkManager> network);
    
    void addDevice(const DeviceInfo& info);
    void removeDevice(const QString& deviceId);
    QList<DeviceInfo> getAllDevices() const;
    
signals:
    void deviceAdded(const DeviceInfo& info);
    void deviceRemoved(const QString& deviceId);
    void errorOccurred(const QString& error);
    
private:
    std::shared_ptr<Core::IDatabase> m_database;
    std::shared_ptr<Core::INetworkManager> m_network;
    QList<DeviceInfo> m_devices;
};

// 数据访问层 (Data Access Layer)
class DatabaseManager : public QObject, public Core::IDatabase {
    Q_OBJECT
public:
    explicit DatabaseManager(QObject *parent = nullptr);
    
    bool connect(const QString& connectionString) override;
    bool execute(const QString& query) override;
    QVariant getValue(const QString& key) override;
    
    // 特定业务方法
    bool saveDevice(const DeviceInfo& info);
    DeviceInfo loadDevice(const QString& deviceId);
    QList<DeviceInfo> loadAllDevices();
    
private:
    QSqlDatabase m_database;
    QString m_connectionString;
};
```

### MVC模式在Qt中的应用
```cpp
// Model - 数据模型
class DeviceModel : public QAbstractTableModel {
    Q_OBJECT
public:
    explicit DeviceModel(QObject *parent = nullptr);
    
    // QAbstractTableModel接口实现
    int rowCount(const QModelIndex &parent = QModelIndex()) const override;
    int columnCount(const QModelIndex &parent = QModelIndex()) const override;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
    QVariant headerData(int section, Qt::Orientation orientation, 
                       int role = Qt::DisplayRole) const override;
    
    // 业务方法
    void addDevice(const DeviceInfo& info);
    void removeDevice(int row);
    void updateDevice(int row, const DeviceInfo& info);
    
private:
    QList<DeviceInfo> m_devices;
};

// View - 视图
class DeviceView : public QTableView {
    Q_OBJECT
public:
    explicit DeviceView(QWidget *parent = nullptr);
    
    void setDeviceModel(DeviceModel *model);
    
signals:
    void deviceSelected(const DeviceInfo& info);
    void deviceDoubleClicked(const DeviceInfo& info);
    
private slots:
    void onSelectionChanged(const QItemSelection &selected, 
                           const QItemSelection &deselected);
    void onDoubleClicked(const QModelIndex &index);
};

// Controller - 控制器
class DeviceController : public QObject {
    Q_OBJECT
public:
    explicit DeviceController(DeviceModel *model, DeviceView *view, 
                             QObject *parent = nullptr);
    
public slots:
    void addDevice();
    void removeDevice();
    void editDevice();
    void refreshDevices();
    
private slots:
    void onDeviceSelected(const DeviceInfo& info);
    void onDeviceDoubleClicked(const DeviceInfo& info);
    
private:
    DeviceModel *m_model;
    DeviceView *m_view;
    DeviceInfo m_selectedDevice;
};
```

## 依赖注入和控制反转

### 依赖注入容器
```cpp
// 简单的依赖注入容器
class DIContainer {
public:
    template<typename Interface, typename Implementation>
    void registerSingleton() {
        m_singletons[typeid(Interface).name()] = 
            []() -> std::shared_ptr<void> {
                return std::make_shared<Implementation>();
            };
    }
    
    template<typename Interface>
    std::shared_ptr<Interface> resolve() {
        auto it = m_singletons.find(typeid(Interface).name());
        if (it != m_singletons.end()) {
            return std::static_pointer_cast<Interface>(it->second());
        }
        return nullptr;
    }
    
private:
    std::map<std::string, std::function<std::shared_ptr<void>()>> m_singletons;
};

// 使用示例
void setupDependencies(DIContainer& container) {
    container.registerSingleton<Core::IDatabase, DatabaseManager>();
    container.registerSingleton<Core::INetworkManager, NetworkManager>();
    container.registerSingleton<BusinessLogic, BusinessLogic>();
}
```

### 工厂模式实现
```cpp
// 抽象工厂
class UIComponentFactory {
public:
    virtual ~UIComponentFactory() = default;
    virtual std::unique_ptr<QWidget> createButton(const QString& text) = 0;
    virtual std::unique_ptr<QWidget> createLabel(const QString& text) = 0;
    virtual std::unique_ptr<QDialog> createDialog(const QString& title) = 0;
};

// 具体工厂实现
class ModernUIFactory : public UIComponentFactory {
public:
    std::unique_ptr<QWidget> createButton(const QString& text) override {
        auto button = std::make_unique<QPushButton>(text);
        button->setStyleSheet(
            "QPushButton {"
            "    background-color: #007ACC;"
            "    color: white;"
            "    border: none;"
            "    padding: 8px 16px;"
            "    border-radius: 4px;"
            "}"
            "QPushButton:hover {"
            "    background-color: #005A9E;"
            "}"
        );
        return button;
    }
    
    std::unique_ptr<QWidget> createLabel(const QString& text) override {
        auto label = std::make_unique<QLabel>(text);
        label->setStyleSheet(
            "QLabel {"
            "    color: #333333;"
            "    font-size: 14px;"
            "}"
        );
        return label;
    }
    
    std::unique_ptr<QDialog> createDialog(const QString& title) override {
        auto dialog = std::make_unique<QDialog>();
        dialog->setWindowTitle(title);
        dialog->setStyleSheet(
            "QDialog {"
            "    background-color: #F5F5F5;"
            "}"
        );
        return dialog;
    }
};
```

## 配置管理和插件架构

### 配置管理系统
```cpp
class ConfigurationManager : public QObject {
    Q_OBJECT
public:
    static ConfigurationManager& instance();
    
    void loadConfiguration(const QString& configFile);
    void saveConfiguration(const QString& configFile);
    
    template<typename T>
    T getValue(const QString& key, const T& defaultValue = T{}) const {
        return m_settings.value(key, QVariant::fromValue(defaultValue)).value<T>();
    }
    
    template<typename T>
    void setValue(const QString& key, const T& value) {
        m_settings.setValue(key, QVariant::fromValue(value));
        emit configurationChanged(key);
    }
    
signals:
    void configurationChanged(const QString& key);
    
private:
    ConfigurationManager() = default;
    QSettings m_settings;
};
```

### 插件架构设计
```cpp
// 插件接口
class IPlugin {
public:
    virtual ~IPlugin() = default;
    virtual QString name() const = 0;
    virtual QString version() const = 0;
    virtual bool initialize() = 0;
    virtual void shutdown() = 0;
    virtual QWidget* createWidget() = 0;
};

// 插件管理器
class PluginManager : public QObject {
    Q_OBJECT
public:
    static PluginManager& instance();
    
    void loadPlugins(const QString& pluginDir);
    void unloadPlugins();
    
    QList<IPlugin*> getPlugins() const;
    IPlugin* getPlugin(const QString& name) const;
    
signals:
    void pluginLoaded(IPlugin* plugin);
    void pluginUnloaded(const QString& name);
    
private:
    QList<QPluginLoader*> m_loaders;
    QList<IPlugin*> m_plugins;
};
```

## 线程和并发架构

### 线程池管理
```cpp
class ThreadPoolManager : public QObject {
    Q_OBJECT
public:
    static ThreadPoolManager& instance();
    
    template<typename Func>
    QFuture<void> submitTask(Func&& func) {
        return QtConcurrent::run(&m_threadPool, std::forward<Func>(func));
    }
    
    template<typename Func, typename Result = std::invoke_result_t<Func>>
    QFuture<Result> submitTaskWithResult(Func&& func) {
        return QtConcurrent::run(&m_threadPool, std::forward<Func>(func));
    }
    
    void setMaxThreadCount(int maxThreads);
    int maxThreadCount() const;
    
private:
    ThreadPoolManager() = default;
    QThreadPool m_threadPool;
};
```

### 异步操作封装
```cpp
class AsyncOperation : public QObject {
    Q_OBJECT
public:
    template<typename Func>
    static QFuture<void> execute(Func&& operation) {
        auto promise = std::make_shared<QPromise<void>>();
        auto future = promise->future();
        
        QtConcurrent::run([promise, operation = std::forward<Func>(operation)]() {
            try {
                operation();
                promise->finish();
            } catch (...) {
                promise->setException(std::current_exception());
            }
        });
        
        return future;
    }
    
    template<typename Func, typename Result = std::invoke_result_t<Func>>
    static QFuture<Result> executeWithResult(Func&& operation) {
        return QtConcurrent::run(std::forward<Func>(operation));
    }
};
```
