KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I have a list of jobs queued in the database which I need to read from database and execute them in parallel using threading and I have a list of command classes to execute each of those jobs all implementing a common interface (command pattern). but when I retrieve the pending jobs from the database, I will need to instantiate the right command object for each job something like this (in a factory class) ICommand command; switch (jobCode) { case "A": command = new CommandA(); break; case "B": command = new CommandB(); break; case "C": command = new CommandC(); break; } command.Execute(); Is there a better way to create the right command object without using a big switch statement like above? OR is there any other pattern for executing the queued jobs? Solution: solved like this (based on the selected answer). This will do lazy instantiation of the command objects. public class CommandFactory { private readonly IDictionary<string, Func<ICommand>> _commands; public CommandFactory() { _commands = new Dictionary<string, Func<ICommand>> { {"A", () => new CommandA()}, {"B", () => new CommandB()}, {"C", () => new CommandC()} }; } public ICommand GetCommand(string jobKey) { Func<ICommand> command; _commands.TryGetValue(jobKey.ToUpper(), out command); return command(); } } Client: var factory = new CommandFactory(); var command = factory.GetCommand(jobKey); command.Execute();
Tags (comma-separated)
Save Edits
Cancel