I’m writing a basic tic tac toe game in Java.
In my Board class I have a swing window which determines which button was pressed.
TttGame is the class which has a Board object.
The goal of this board is not to act as a fully functional tic-tac-toe board but to serve as a framework where the TttGame class controls all the logic. As such I need the Board to send some kind of event when the button is pressed to the TttGame class with the id of the button that has been pressed.
What is the simplest method of doing this?
edit: I found something called the Observer pattern – Is this the simplest method of doing this?
Yes, the Observer pattern is what you want to apply here. Create a Listener interface (
BoardListener) perhaps like this:Then maintain a
SetorListof listeners in yourBoardclass and cycle through them, calling squareSelected on each, when a square is chosen.I would look into the Model-View-Controller pattern however, in which the View listens to the Model for changes, and the Controller detects user actions and changes the model accordingly.