C++简单实现调用链管理器

#include <iostream>
#include <vector>
#include <functional>
#include <string>
#include <unordered_map>
#include <algorithm>
#include <stack>

class CallChainManager {
public:
    // 注册一个函数到调用链中,可指定多个前置节点
    // 返回true表示注册成功,false表示检测到依赖环
    bool registerFunc(std::function<void()> func, 
                     std::string name, 
                     std::vector<std::string> previousNames = {}) {
        // 临时添加新节点检查是否有环
        size_t newIndex = functions.size();
        functions.push_back({func, name, previousNames});
        nameToIndices[name].push_back(newIndex);
        
        bool hasCycle = hasCyclicDependency(newIndex);
        if (hasCycle) {
            // 如果检测到环,撤销添加
            functions.pop_back();
            nameToIndices[name].pop_back();
            if (nameToIndices[name].empty()) {
                nameToIndices.erase(name);
            }
            return false;
        }
        return true;
    }

    // 执行调用链
    void ExecutionCallChain() {
        std::vector<bool> executed(functions.size(), false);
        size_t executedCount = 0;
        
        while (executedCount < functions.size()) {
            bool hasProgress = false;
            
            for (size_t i = 0; i < functions.size(); ++i) {
                if (!executed[i]) {
                    // 检查是否所有前置节点都已执行
                    bool canExecute = true;
                    for (const auto& prevName : functions[i].previousNames) {
                        auto it = nameToIndices.find(prevName);
                        if (it != nameToIndices.end()) {
                            for (auto idx : it->second) {
                                if (!executed[idx]) {
                                    canExecute = false;
                                    break;
                                }
                            }
                        }
                        if (!canExecute) break;
                    }
                    
                    if (canExecute) {
                        functions[i].func();  // 执行函数
                        executed[i] = true;
                        executedCount++;
                        hasProgress = true;
                    }
                }
            }
        }
    }

    // 打印当前调用链的拓扑结构(用于调试)
    void printCallChain() const {
        std::cout << "Call Chain Structure:" << std::endl;
        for (size_t i = 0; i < functions.size(); ++i) {
            std::cout << "[" << i << "] " << functions[i].name;
            if (!functions[i].previousNames.empty()) {
                std::cout << " (depends on: ";
                for (const auto& dep : functions[i].previousNames) {
                    std::cout << dep << " ";
                }
                std::cout << ")";
            }
            std::cout << std::endl;
        }
    }

private:
    // 存储函数节点信息
    struct FunctionNode {
        std::function<void()> func;
        std::string name;
        std::vector<std::string> previousNames;
    };
    
    std::vector<FunctionNode> functions;
    std::unordered_map<std::string, std::vector<size_t>> nameToIndices;

    // 检测从指定节点出发是否存在循环依赖
    bool hasCyclicDependency(size_t startIndex) const {
        std::vector<bool> visited(functions.size(), false);
        std::vector<bool> recursionStack(functions.size(), false);
        std::stack<size_t> stack;

        stack.push(startIndex);
        visited[startIndex] = true;
        recursionStack[startIndex] = true;

        while (!stack.empty()) {
            size_t current = stack.top();
            bool hasUnvisitedChild = false;

            // 检查当前节点的所有前置节点
            for (const auto& prevName : functions[current].previousNames) {
                auto it = nameToIndices.find(prevName);
                if (it != nameToIndices.end()) {
                    for (auto prevIndex : it->second) {
                        if (!visited[prevIndex]) {
                            visited[prevIndex] = true;
                            recursionStack[prevIndex] = true;
                            stack.push(prevIndex);
                            hasUnvisitedChild = true;
                            break;
                        } else if (recursionStack[prevIndex]) {
                            // 发现环
                            return true;
                        }
                    }
                    if (hasUnvisitedChild) break;
                }
            }

            if (!hasUnvisitedChild) {
                recursionStack[current] = false;
                stack.pop();
            }
        }

        return false;
    }
};

// 测试代码
int main() {
    CallChainManager manager;
    
    // 注册一些测试函数
    bool success = true;
    success &= manager.registerFunc([]() { std::cout << "Function A1 executing" << std::endl; }, "A");
    success &= manager.registerFunc([]() { std::cout << "Function B1 executing" << std::endl; }, "B", {"A"});
    success &= manager.registerFunc([]() { std::cout << "Function C executing" << std::endl; }, "C", {"B"});
    success &= manager.registerFunc([]() { std::cout << "Function D executing" << std::endl; }, "D", {"A", "B"});
    
    // 尝试创建环(A -> B -> C -> A)
    bool cyclicResult = manager.registerFunc([]() { std::cout << "Function A2 executing" << std::endl; }, "A", {"C"});
    std::cout << "Register A2 (creates cycle): " << (cyclicResult ? "Success" : "Failed (expected)") << std::endl;
    
    success &= manager.registerFunc([]() { std::cout << "Function B2 executing" << std::endl; }, "B", {"D"});
    
    // 打印调用链结构
    manager.printCallChain();
    
    if (success) {
        std::cout << "\nExecuting call chain..." << std::endl;
        manager.ExecutionCallChain();
        std::cout << "Call chain executed successfully!" << std::endl;
    } else {
        std::cerr << "\nFailed to register all functions due to dependency cycles" << std::endl;
    }
    
    return 0;
}
posted @ 2025-12-10 10:31  乌合之众  阅读(4)  评论(0)    收藏  举报
clear