From the course: Programming Foundations: Design Patterns
Unlock the full course today
Join today to access over 24,100 courses taught by industry experts.
Using the Observer pattern
From the course: Programming Foundations: Design Patterns
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…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.