Search code examples
javalanguage-agnosticobserver-pattern

Understanding the Observer Pattern


I have built a small app that has a JSlider which controls the speed of an object. When the slider detects a change in its state, the object's speed changes appropriately. I was wondering if what I built utilized the Observer Pattern. Wikipedia states that an Observer Pattern "is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems". Within my code, whenever a change in the JSlider is detected a small piece of code is automatically executed to change the object's speed via:

slider.addChangeListener(
            new ChangeListener(){
                public void stateChanged(ChangeEvent e){
                    horizSpeed = slider.getValue();
                    sliderTitle.setText("Current Speed: " + horizSpeed);
                }
            }
    );

I don't think it maintains a list of dependents as Wikipedia calls for but I'm not sure. If anyone could enlighten me on the subtleties of the Observer Pattern, I would greatly appreciate it. Thanks!


Solution

  • Slider is the subject and addChangeListener adds a dependant to its list of dependents. This is a classic example of the observer pattern.