From the course: Programming Foundations: Design Patterns

Unlock the full course today

Join today to access over 22,500 courses taught by industry experts or purchase this course individually.

Using the Observer pattern

Using the Observer pattern

From the course: Programming Foundations: Design Patterns

Start my 1-month free trial

Using the Observer pattern

- [Instructor] Let's take a look at the Java code to implement our basic observer pattern design. We'll start with the Subject interface. This specifies the three methods the concrete subject must implement, registerObserver, to allow observers to register themselves, removeObserver, to allow observers to stop participating, and notifyObservers, which will make sure all the observers are notified if the data in the subject changes. The concrete subject, named SimpleSubject here, implements that interface, and so must implement those three methods. The SimpleSubject manages the list of observers, in this case, using an ArrayList. And, it manages the data that the observers are interested in. Here, that's just an integer, value. Observers call registerObserver to add themselves to the list of observers in the subject. And they call removeObserver to remove themselves from the list. Let's say the value in the subject changes. Perhaps, another object calls setValue to change the value…

Contents