Java Reference
In-Depth Information
UI Frameworks are another place where observers are heavily used, although this is more related
to desktop applications, not enterprise applications. In the context of UI frameworks, the observer
pattern is often referred to as the listener pattern. Essentially, these patterns are the same. Button
click listeners, drag drop handlers, and value change listeners all rely on an implementation of the
observer pattern.
Almost all web frameworks are built on the model‐view‐controller pattern, which also uses the
observer pattern internally. See Chapter 14, “Model View Controller Pattern,” for more details.
For a long time, part of my daily job has been to mentor interns and fresh
graduates. This war story goes back to a talented intern I had the chance to work
with. This bright electronics graduate had more experience with hardware and
structural programming than object‐oriented languages; therefore, she had little
knowledge of design patterns. She had just completed a successful Arduino‐based
project. 3
We started developing an Android application that used Android's built‐in face
detection feature to detect whether the user was in front of the device. Coming
from an Arduino project, the intern's i rst approach was to create a loop to query
the camera and see if it had detected a new face. This loop was running in the main
application thread, so it was blocking on the application.
After realizing that she had locked the UI thread, she decided to create a separate
thread to perform the face detection job. She was using the “if the only tool you
have is a hammer, every problem looks like a nail” approach. 4 We chatted for a
while about how the Arduino application was structured. On the Arduino, the
whole application was a loop that we wanted to keep running until we stopped
it, and all program features were handled in that loop. However, our Android
application had a different structure. The application needed to be informed of
when there was a face detected rather than querying the camera to see if a face had
been detected. Once this graduate understood how observers work, she didn't have
much difi culty implementing the pattern because the Android system was already
built on the observer pattern. All she needed to do was add the appropriate listener
class and perform whatever function she needed when a face was detected.
Observer Class Diagram
As can be seen from Figure 11-1, the observer pattern introduces an Observer interface that all
concrete observers must implement. This interface has just one method that is called by the subject
to notify the observers that there has been a change in state. Each subject holds a list of registered
observers and calls the notifyObservers method to inform the registered observers about any
updates or changes in the subject. It has methods for registering and unregistering observers.
Search WWH ::

Custom Search