问题
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. 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. 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? Thanks for helping a new programmer out! =D
回答1:
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.
回答2:
I agree that Builder and Factory Method make sense here. 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. Just use a static factory method that takes the name of the Command class to instantiate.
来源:https://stackoverflow.com/questions/10955986/design-pattern-for-c-sharp-and-invoking-different-methods-based-on-a-string-para