Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To use or not to use the State Pattern?

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?

like image 436
Robert Avatar asked Jan 27 '10 19:01

Robert


1 Answers

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.

like image 100
RossFabricant Avatar answered Nov 03 '22 12:11

RossFabricant