在C++中,switch
语句通常用于处理基于单个变量的多个条件分支。然而,switch
语句的扩展性有限,因为它要求每个条件分支都有一个唯一的常量表达式。为了提高switch
语句的扩展性,可以考虑以下几种设计模式:
将每个条件分支映射到一个函数指针或函数对象,这样可以避免使用switch
语句。
#include <iostream>
#include <map>
#include <functional>
void handleCase1() {
std::cout << "Handling case 1" << std::endl;
}
void handleCase2() {
std::cout << "Handling case 2" << std::endl;
}
void handleCase3() {
std::cout << "Handling case 3" << std::endl;
}
int main() {
std::map<int, std::function<void()>> cases = {
{1, handleCase1},
{2, handleCase2},
{3, handleCase3}
};
int caseValue = 2;
if (cases.find(caseValue) != cases.end()) {
cases[caseValue]();
} else {
std::cout << "No handler for case " << caseValue << std::endl;
}
return 0;
}
std::variant
和std::visit
C++17引入了std::variant
和std::visit
,可以用来处理多种类型的情况。
#include <iostream>
#include <variant>
#include <string>
struct CaseHandler {
void operator()(const std::string& message) const {
std::cout << message << std::endl;
}
};
struct Case1Handler {
void operator()(const std::string& message) const {
std::cout << "Handling case 1: " << message << std::endl;
}
};
struct Case2Handler {
void operator()(const std::string& message) const {
std::cout << "Handling case 2: " << message << std::endl;
}
};
int main() {
std::variant<CaseHandler, Case1Handler, Case2Handler> handler;
handler = Case1Handler{};
std::visit([](auto&& arg) { std::forward<decltype(arg)>(arg)(); }, handler);
return 0;
}
策略模式是一种行为设计模式,可以将每个条件分支封装成一个策略类。
#include <iostream>
#include <memory>
class HandlerStrategy {
public:
virtual ~HandlerStrategy() = default;
virtual void handle() const = 0;
};
class Case1Handler : public HandlerStrategy {
public:
void handle() const override {
std::cout << "Handling case 1" << std::endl;
}
};
class Case2Handler : public HandlerStrategy {
public:
void handle() const override {
std::cout << "Handling case 2" << std::endl;
}
};
class Case3Handler : public HandlerStrategy {
public:
void handle() const override {
std::cout << "Handling case 3" << std::endl;
}
};
int main() {
std::unique_ptr<HandlerStrategy> handler = std::make_unique<Case1Handler>();
handler->handle();
handler = std::make_unique<Case2Handler>();
handler->handle();
handler = std::make_unique<Case3Handler>();
handler->handle();
return 0;
}
将每个条件分支映射到一个枚举值,并使用函数指针或lambda表达式来处理每个枚举值。
#include <iostream>
#include <functional>
enum class Case {
Case1,
Case2,
Case3
};
void handleCase1() {
std::cout << "Handling case 1" << std::endl;
}
void handleCase2() {
std::cout << "Handling case 2" << std::endl;
}
void handleCase3() {
std::cout << "Handling case 3" << std::endl;
}
int main() {
Case caseValue = Case::Case1;
std::function<void()> handlers[] = {
[]() { handleCase1(); },
[]() { handleCase2(); },
[]() { handleCase3(); }
};
if (caseValue >= 0 && caseValue < sizeof(handlers) / sizeof(handlers[0])) {
handlers[caseValue]();
} else {
std::cout << "No handler for case " << static_cast<int>(caseValue) << std::endl;
}
return 0;
}
通过这些设计模式,可以提高switch
语句的扩展性,使其更容易适应新的条件分支。