This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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
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. Regards, Kenny