重构一个长 servlet 条件
我有一个 servlet,它可以接受多达两打不同类型的请求(在 servlet 中称为命令)。创建了一个非常大的条件来为这些请求提供服务,其结构如下:
if (command.equals("Command1"))
doSomething();
else if (command.equals("Command2))
doSomethingElse();
else if (command.equals("Command3))
doThisOtherThing();
......
是否有更好的方法来编写此代码?我正在阅读一本关于 JUnit 测试的书,其中建议在条件上使用多态性,但我只是不知道如何在这个示例中执行此操作。有人有更好的主意吗?
谢谢你,
埃利奥特
I have a servlet which can accept upwards of two dozen different kinds of requests (called commands in the servlet). A very large conditional was created to service to these requests structured like this:
if (command.equals("Command1"))
doSomething();
else if (command.equals("Command2))
doSomethingElse();
else if (command.equals("Command3))
doThisOtherThing();
......
Is there a better way to write this code? I'm reading a book on JUnit testing that suggests using polymorphism over conditionals but I just don't see how to do this in this example. Does anyone have a better idea?
Thank you,
Elliott
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
鉴于您正在使用 Servlet,您正在寻找的是 FrontController。基本思想很简单,您拥有的每个命令字符串都可能被映射到一个 Map 中,并且您会将操作移交给这些命令。
一个非常简单的实现可能如下所示:
这消除了对 if/switch 的需要,并且您可以将每个命令作为一个特定的类,从而改进您的代码组织。
显然,这是重新发明轮子,因为 Java 中的所有 Web MVC 框架(如 Struts、SpringMVC、VRaptor 和 Play)都实现了这种模式,并免费为您提供此功能,因此您也可以考虑切换到框架,而不是继续使用纯 servlet并构建您自己的本土 Web 框架。
Given that you're using Servlets, what you're looking for is a FrontController. The basic idea is simple, each of those command Strings you have would possibly be mapped into a Map of and you would hand over the actions to these commands.
A really simple implementation could look like this:
This removes the need of having an if/switch and you can have each command being a specific class, improving your code organization.
Obviously, this is reinventing the wheel as all web MVC frameworks in Java like Struts, SpringMVC, VRaptor and Play implement this pattern and give this functionality for free to you, so you could also think about switching to a framework instead of staying with pure servlets and building your own homegrown web framework.