OBSERVER (Object Behavioral)
Purpose
Lets one or more objects be notified of state changes in other
objects within the system.
Use When
1 State changes in one or more objects should trigger behavior
in other objects
2 Broadcasting capabilities are required.
3 An understanding exists that objects will be blind to the
expense of notification.
Example
This pattern can be found in almost every GUI environment.
When buttons, text, and other fields are placed in applications
the application typically registers as a listener for those controls.
When a user triggers an event, such as clicking a button, the
control iterates through its registered observers and sends a
notification to each.
- package javaPattern.observer;
- import java.util.ArrayList;
- public interface Observer {
- public void update();
- }
- class ConcreteObserver implements Observer{
- @Override
- public void update() {
- System.out.println("update...");
- }
- }
- interface Subject{
- public void attach(Observer o);
- public void detach(Observer o);
- public void notifyObserver();
- }
- class ConreteSubject implements Subject{
- private ArrayList<Observer> observers = new ArrayList<Observer>();
- @Override
- public void attach(Observer o) {
- observers.add(o);
- }
- @Override
- public void detach(Observer o) {
- observers.remove(o);
- }
- @Override
- public void notifyObserver() {
- for(Observer o : observers){
- o.update();
- }
- }
- }
- class Client{
- public static void main(String[] args) {
- Subject subject = new ConreteSubject();
- Observer observer1 = new ConcreteObserver();
- Observer observer2 = new ConcreteObserver();
- Observer observer3 = new ConcreteObserver();
- subject.attach(observer1);
- subject.attach(observer2);
- subject.attach(observer3);
- subject.notifyObserver();
- }
- }