简体   繁体   English

C#的设计模式,并根据字符串参数调用不同的方法

[英]Design Pattern for C# and invoking different methods based on a string parameter

So I am currently about to develop a rather cool library in which I will pull data from an Excel Worksheet or Sharepoint List and then use WatiN and .NET with C# to execute various browser commands for automated UI testing. 因此,我目前正在开发一个相当酷的库,我将从Excel工作表或Sharepoint列表中提取数据,然后使用WatiN和.NET与C#执行各种浏览器命令以进行自动UI测试。 However, I am running into a big design issue in trying to encapsulate the changing requirements that future commands or tests may need to be generated. 但是,在尝试封装可能需要生成未来命令或测试的不断变化的需求时,我遇到了一个大的设计问题。 Currently, I have about 5 unique actions that I need to perform based on a command parameter (stored as a string in the Excel or Sharepoint List), but I would like to easily make the number of commands extensible as well as perform validation to ensure no bad commands. 目前,我需要基于命令参数(在Excel或Sharepoint列表中存储为字符串)执行大约5个独特的操作,但我想轻松地使命令数量可扩展以及执行验证以确保没有错误的命令。 Can anyone point me in the right direction for Design Patterns that might help me implement this efficiently and robustly rather than just writing one giant switch statement in a HandleCommand() function? 任何人都可以指出我正在设计模式的方向,这可能有助于我有效和健壮地实现这一点,而不是只在HandleCommand()函数中编写一个巨大的switch语句? Thanks for helping a new programmer out! 感谢您帮助新的程序员! =D = d

Look at the command pattern to encapsulate the commands and use the factory pattern to create the instance of the command object based on its name. 查看命令模式以封装命令,并使用工厂模式根据其名称创建命令对象的实例。 The factory can use reflection to determine which command to create based on the text. 工厂可以使用反射来确定基于文本创建的命令。

I agree that Builder and Factory Method make sense here. 我同意Builder和Factory Method在这里有意义。 You probably don't want to use the inheritance-based version of Factory Method as described in the "Design Patterns" book by Gamma and co. 您可能不希望使用Gamma和co的“设计模式”一书中描述的基于继承的版本的工厂方法。 Just use a static factory method that takes the name of the Command class to instantiate. 只需使用一个静态工厂方法,该方法将Command类的名称实例化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM