避免一千个 if 语句的最佳方法是什么?
我基本上有这个问题:现在,我们有一个系统,它获取一个字符串作为输入,它基本上说的是 ACTION:。
对于每个动作都有一个自动生成的函数(Rational Rose GRRR),例如
bouncer_comm.chatMessage("data goes here").sendAt(msg->sapIndex0());
bouncer_comm.askforname().sendAt(msg->sapindex0());
bouncer_comm
返回一个 RTOutSignal
,由于结构奇怪,我无法手动创建它们玫瑰用途。
现在,我唯一的选择是创建一百个左右的 if 语句,我这样做:
if(action == "CHAT") bouncer_comm.chatMessage("data goes here").sendAt(msg->sapIndex0());
这真的很烦人。
避免这种情况的最佳方法是什么? 我已经看过/尝试了无数的事情,这是一个非常旧的版本的rationalrose(2k之前),是的。
如果有人有任何想法那就太棒了。
I basically have this problem: right now, we have a system where it gets a string as input, and it basically says ACTION:.
For each of the actions there is an automatically generated function(Rational Rose GRRR), such as
bouncer_comm.chatMessage("data goes here").sendAt(msg->sapIndex0());
bouncer_comm.askforname().sendAt(msg->sapindex0());
bouncer_comm
returns an RTOutSignal
, I can't create them manually because of the bizarre structure rose uses.
Right now, my only option is to create a hundred or so if statements, where I do:
if(action == "CHAT") bouncer_comm.chatMessage("data goes here").sendAt(msg->sapIndex0());
Which is realllllyy annoying.
What would be the best way to avoid this? I've looked at / tried countless things, this is a really old version of rational rose (pre 2k) and yeah.
If anyone has any ideas that would be amazing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我喜欢@cobbal 上面的函数指针哈希的想法,但是您可以用多态性替换这个条件逻辑。
请参阅:http://c2.com/cgi/wiki?ReplaceConditionalWithPolymorphism
I like @cobbal's idea of the function pointer hash above, but you could replace this conditional logic with polymorphism.
see: http://c2.com/cgi/wiki?ReplaceConditionalWithPolymorphism
存储函数指针的哈希在这里可以很好地工作
A hash storing function pointers could work well here
我使用了多态性与工厂模式相结合。 我减少了很多如果:
I used polymorphism combined with the factory pattern. I reduced a lot of if's to this :
我认为最简单的是 boost::functions 的映射。
I think the easiest is a map of boost::functions.
您可以使用 boost::bind 或 boost::function 和地图。 这将允许您调用正确的函数,即使知道每个函数具有不同数量的参数。
如果您不需要任何额外的代码,您可以使用函数对象和继承。
You could use boost::bind or boost::function and a map. This would allow you to call the correct function, even know each function has a different amount of parameters.
If you don't want any extra code you could use function objects and inheritance.