Observer pattern? Where do i get examples of this in Java (i know google but was hoping for some personal insight also.)
On to a proper explanation of my issue:
i have 3 forms/windows. “board” is the main form that loads as the application.
“chat” is where the text chat takes place.
“network” is where network connection is established.
i have the game (connect4) working locally and i would like to implement a networked version of it also.
my idea is maybe it is related to Observer pattern to have a thread (or something) monitoring network state during runtime and update the chat and board forms of the current network status as well as delivering received data from the network.
are my ideas valid? or how should i go about establishing network and network status updates throughout the application?
thank you for your input.
board http://img39.imageshack.us/img39/5221/boardz.jpg
chat http://img691.imageshack.us/img691/3629/chatos.jpg
network http://img441.imageshack.us/img441/5906/networks.jpg
EDIT: is there a book on Java Observer pattern any one can recommend?
In this instance the chat and game windows would be considered Observers. You’ll want to implement an interface called something like Observers (the java API has a native Observer pattern at java.util.Observer but you can implement your own) and have your chat and board window implement them. You might have it look like:
postUpdate is a function that all of the Observers will need to define, and both these classes and anything else you want to include later will need to implement Observer, like:
Then, in your network class, you’ll want a method like
Then, during initialization, you will want to want to call the addObserver function from each Observer you want to have watching it, and have some logic in your network class to update everybody who has registered by calling their postUpdate functions. In this case I acted as though you want to send them a String containing new data, that is only one option. You could also have it pass nothing and just act as notification that an update has occured in which case the Observers will be responsible for checking if the data they care about from the network has changed; or maybe you could have it pass some data representing what exactly has been updated on the network, such that the class could know if it cares about what has changed (for example, the gameboard might not care if the only change has occured to chat data, so it won’t bother doing anything else).
You may find best success investigating Head First Design Patterns, in terms of books.