用什么替换巨型switch语句? [英] Replace giant switch statement with what?

查看:214
本文介绍了用什么替换巨型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 ++,但我想这个问题存在于任何语言。这是更多关于算法和OO设计我猜。只有重要的是,这必须编译,即使我想我不能有任何动态/ eval'd代码。

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.

更新:我也关注此评论

推荐答案

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

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

这篇关于用什么替换巨型switch语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆