Reputation: 8609
I'm designing a pinball game for a Uni project in which there are supposed to be 2 modes: running mode and builder mode, whereby one can design/redesign the layout of the machine.
My initial thought was the State pattern - however, I'm concerned that the common interface between the states may contract them into implementing methods which are not appropriate to that state.
Eg. In the builder mode it would be wholly appropriate to set the position of a bumper or whatever; but in running mode it would be implemented as doing nothing or throwing an exception - which just seems nasty, especially if there are many such methods.
Is there a better design for this?
Upvotes: 5
Views: 642
Reputation: 129247
A couple of years ago I had a similar assignment at university.
I would say using the state pattern is overkill for this, as well as not being entirely suited, as previously mentioned. What we did with this assignment is:
Basically, as mentioned elsewhere, the two modes do not share enough commonality to really justify the state pattern here.
There is one possibility of applying the state pattern, which would make sense. Since it's a university assignment, there's likely to be credit for the thought and justification behind it. It is related to the "level above" I mentioned earlier. In my experience this was part of the GUI that was independent of the mode. It allowed things like closing the application, opening previous pinball configurations, and switching between the modes. What it could also do is show context dependent menu items. The state of the menus could be retrieved from the current mode. So the builder mode could include save and other builder specific actions, and the running mode could offer play/pause options. If you have spent the time investigating the state pattern, and wish for that to pay off, this would be a possible option.
P.S. Murray did seem enthusiastic about our use of design patterns at the time ;-)
Upvotes: 1
Reputation: 12492
Your intuition is correct. The State pattern is helpful when a program can have many different states, each one supporting many of the same operations. For example a drawing program may have many different tools, but each one supports similar operations like putting the pen down or up, and drawing a line between 2 points.
In your case there are only 2 states, and they don't share much behavior. The main thing they share is common GUI operations which are probably already in a standard library. You do need to ensure that code for things like displaying the bumpers is not duplicated, but you can do that without the State pattern.
Upvotes: 11