dimanche 30 octobre 2016

Design a java based menu so that it's easier to add new options

I am trying to create a java application which displays a Menu with few options. Each option selection performs some independent operation say executing a script or performing some db operation etc
eg:
1 option1title
2 option2title
3 option3title
...

I need to design this such that I should be able to add new options easily. say just by adding a new class.
Some options might show a submenu as well.

Design thoughts that I have

Have an interface say "IOption" with methods like optionTitle, optionAcion. So each "Option" in the menu would implement this interface and write its action & title.
How do I display the menu ?
I can have a class which where each option is registered. Say a list of all the options. Then my main program would iterate over this classes and shows the menu. Option selection would call the action of that particular class.
Else I can use reflection/annotation to get the all the classes which implement this interface and show the menu ----> This might be an overkill.

Is there any better way to design this ? Any design patterns that I can bring in ? My priority is good design.
With my solution also If I want to add a new option, I would need to register each option in a list, implement the class etc.
Instead of adding to a list in register class, how about having the optionTitle <-> class info in an xml file or something ?
And I'll have submenus as well. Other than writing this in the itemAction method, any better way to design this ?

Let me know If I need to add more info.

Aucun commentaire:

Enregistrer un commentaire