用什么替换巨大的 switch 语句?

我有一个解析一些模板文件的代码,当它找到一个占位符时,它会用一个值替换它.比如:

I have a code that parses some template files and when it finds a placeholder, it replaces it with a value. Something like:

<html>
<head>
    <title>%title%</title>
</head>
<body bgcolor="%color%">
...etc.

在代码中,解析器找到这些,调用这个函数:

In code, the parser finds those, calls this function:

string getContent(const string& name)
{
    if (name == "title")
        return page->getTitle();
    else if (name == "color")
        return getBodyColor();
    ...etc.
}

然后用返回值替换原来的占位符.

and then replaces the original placeholder with returned value.

在实际情况下,它不是一个虚拟网页,并且可能出现许多 (50+) 个不同的占位符.

In real case, it is not a dummy web page, and there are many (50+) different placeholders that can occur.

我的代码是 C++,但我猜任何语言都存在这个问题.我猜这更多是关于算法和面向对象设计的.唯一重要的是它必须被编译,即使我想要我不能有任何动态/评估代码.

My code is C++, but I guess this problem exists with any language. It's more about algorithms and OO design I guess. Only important thing is that this must be compiled, even if I wanted I couldn't have any dynamic/eval'd code.

我虽然想实施责任链模式,但似乎不会对这种情况有太大??改善.

I though about implementing Chain of Responsibility pattern, but it doesn't seem it would improve the situation much.

更新:我也担心 此评论在另一个线程中.我应该关心它吗?

UPDATE: and I'm also concerned about this comment in another thread. Should I care about it?

推荐答案

使用将标签名称映射到标签处理程序的字典.

Use a dictionary that maps tag names to a tag handler.

相关文章