This post originated from an RSS feed registered with Java Buzz
by Marc Logemann.
Original Post: Use Observer more often
Feed Title: Marc's Java Blog
Feed URL: http://www.logemann.org/day/index_java.xml
Feed Description: Java related topics for all major areas. So you will see J2ME, J2SE and J2EE issues here.
From time to time i am reviewing other peoples code. In doing so, i am constantly missing the usage of the Observer pattern. This mostly when reading J2EE based applications. All this results in tight coupling of different classes and wild object passing in the application itself. It appears to me that Swing developers are more sensitive of this pattern, most likely because this pattern is heavily used all over the Swing API, which you can see when you look at all the Listener interfaces and methods.
While some patterns are demanding and not easy to get on the first read, the Observer pattern itself is quite easy and nothing should prevent you from using it. You can even use the Classes/Interfaces (Observer, Observable) provided by Sun to implement this pattern. There are many patterns where such help is not provided by Sun and manual implemenation is a must. But be aware that the Sun Observer imlemenation is somehow limited. By extending from the Observable (mostly called the subject) class, you cant extend your subject from a custom class at the same time. But creating your own Observable/Subject is just a matter of minutes.
So the next time an object changes in your system and you want to inform some other objects about that change. Dont use static instance variables of your interessted object and call the methods manually. Use Observer and the world will be much easier.