Observer Recipe

1) Again, write out your logic so you don’t cry yourself to sleep cause your playing by ear manages to melt your computer and little mice run out with forks and stab your toes.

2) Since I assume that by writing out your logic you know where the pattern is most applicable, we can begin developing the code.  I first wrote the two interfaces Observer and Subject. I am not using Java API observable and such. Give Observer the appropriate methods and same with subject. These should be: Observer :Update(), Subject: NotifyObserver(); RegisterObserver(); and RemoveObserver();

3) okay, a little work in the main, create a variable that references your subject.

4)Now, let’s work with the subject, their some interesting goodies we need to throw in here. The subject you intend to use will of course need to implement the Subject interface we made earlier and thus it’s methods. Fill out the Overloaded method logic for each one. Im sure you know how to do that ;) . Also, we need to create the parameters that set a change and notify the observers. Write out the situationChanged() method, and inside it implement notifyObserver(); the other method to create is setSituation() Which will take in whatever data fields are involved with the observation and set them to be the values with many “this dots” .

5) alright, lets work with our observer(s). first implement the observer interface and add all the necessary methods (namely update();).

6) in your observers constructor, go ahead and use it to register the observer as an observer with constuctor by passing it the Subject object. Use the  Subject.registerObserver(this); code line to do this.

7) fill out the update method, using the applicabel data fields, and follow that good stuff with a display() method to show off your work. Of course, you need to write the display method first though.

8) alright, back to main, remember that object reference you made? well now lets put it to use.  Create new instances of your observers, and pass them the Subject object.

9) finally, we’re going to pass some changing data values, and we’ll hard code these for now, but later when we can afford measuring devices or some such thing we’ll use them. implement a few setSituation() methods, with your data fields in thier, and when you run, your display() method should show the results of your hard work. Well DONE.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.