wood burning stoves
The moose likes Beginning Java and the fly likes Need Help using the Observer design pattern Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Need Help using the Observer design pattern" Watch "Need Help using the Observer design pattern" New topic

Need Help using the Observer design pattern

Rick Katka

Joined: Feb 22, 2004
Posts: 7
I need to create a program that simulates a clock that the user intializes in a JFrame. However I need to design this using the observer design pattern with two observers-->the command line and the GUI JFrame that need to be updated every second. I'm having a hard time figuring out what classes need to know about the others and how to write the subject class for this.
As of right now these are the classes that I have:
CommandLineTime, Driver, JFrameTime,MyTime,Observer,ObserverImpl,Subject
The CommandLineTime and JFrameTime are my observers and have an update method. Subject is my observable class and has methods that attach(Observer 0),detach(Observer 0), and notifyObservers() methods that add or remove the observer objects from an array. The driver is self explainitory.
Thanks for any help in advanced...it is greatly appreciated!
Rick Katka
KR Campbell
Ranch Hand

Joined: Mar 26, 2004
Posts: 124
Assuming that Subject is inheriting from Observable just remember that your notifyObservers() method should call super.notifyObservers(). This can cause a lot of frustration if you forget that you are over-riding the method.
You have an Observable subject to which you are adding two Observers:

Now when you call your notifyObservers() method, aClassWhichImplementsObserver and its friend will call their update() method in which they will do whatever it is that they need to do for their own satisfaction.
The only other point I would make at this stage is that you really should have a full idea of what it is you actually want to do before you invent a list of classes. Driver isn't self-explanatory to me! Subject is doing something that Observers want to know about (such as telling the time). The Observers will do something for themselves such as update their displays when notified. The only other class you might need is a calling class. Is that what Driver is for? What is ObserverImpl? What is MyTime?
Either your program is more complicated than you have indicated or you have more classes than you need to implement the Observer design pattern which is supposed to simplify your code and make it recognisable.
I agree. Here's the link: http://aspose.com/file-tools
subject: Need Help using the Observer design pattern
It's not a secret anymore!