Hi all I am relatively new to OOD and Java hence am not sure how to do this properly.
Currently I need to create an application (console/command prompt based) that involves going through a series of so called "menus" where the application will display your choices and you enter 1/2/3/4 etc. My professor told me to break up my boundary class (the class where all the display of choices is in) because it's too long (400+ lines).
Now comes the problem. If i were to break it up, I would have to keep creating new object classes to call on the different menu in different classes. For example:
Let say I have MainMenu, FoodMenu, DrinkMenu. So my main method will create a MainMenu object to call displayMenu(). From there, if I want to navigate to the food menu, I have to create another FoodMenu object and call displayMenu() under it again. Further along the codes, if i want to navigate back to the main menu, I would then again have to create the MainMenu object again and call displayMenu.
The above method would have so many variables waiting to be garbage collected and a total waste of memory. Is there another solution around this? Thank you very much in advance.
开发者_如何学PythonHamlyn
Make all your menus either extend an abstract class (okay) or implement an interface (better), if you're not already doing that.
As for how to get to the menus, you can just store one of each type of menu in a menu array or some other collection (for example, a Map
if you want to be able to look them up using a string or other object). Have that collection be globally accessible (static
in some public
class) and then you can display the same instance of a menu each time you need it.
First of all, garbage collection problems happen when you have thousands of objects floating around, not... three. So don't even worry about that.
But in general, your thesis that you need to recreate all those objects is flawed. You only need one of each, and they simply need to be able to get access to references to one another. For example, each "displayMenu" method might take a Menu as an argument; that displayMenu() method would set things up so that the "return to previous menu" option invokes the Menu that was passed as an argument.
As discussed in How to Use Actions, the Action
class is a convenient way "to separate functionality and state from a component." This example creates a menu of recent files using instances of the RecentFile
class. A similar class for each of your MainMenu
, FoodMenu
, DrinkMenu
might be a way to encapsulate related menu items.
精彩评论