jeudi 24 septembre 2020

How to best store commands and their response code for a .NET console app?

Description

My app takes user input (ReadLine()) and calls its corresponding function as a result.

At the moment, it's just a switch that checks for certain commands, with their response code inside cases, but I though I ought to separate them for cleaner code.

What's the design pattern of choice here?

Attempted Solution

I could make an abstract Command class with a commandName field and a mandatory Respond() function. Then, I'd hold a List of Commands, iterate over each to check if its commandName matches what the user input, and call its Respond() function (and break the loop) if so.

Problem

That still necessitates manually creating instances of each Command and adding them to the List that holds them.

If possible, I'd like for each Command to be automatically added. I wish to instruct the program to loop over every class in a Commands/ directory and instantiate and add it on its own, or something like that.

Can I do that? If not, what's the best alternative?

Aucun commentaire:

Enregistrer un commentaire