Home
Cloud
Big Data
CI
Install
Samples
Java
Ubuntu
Maven
Archive
Design Patterns
|
Observer
References
Example
The
Observer
The
Concrete Observer
The
Abstract Subject
The
Concrete Subject
A simple class to test the
Observer
design pattern
References
Definition: (
source:
http://en.wikipedia.org/wiki/Observer_pattern
)
The Observer pattern defines an object, called the subject, that maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.
Class diagram: (
source:
http://en.wikipedia.org/wiki/Observer_pattern
)
Example
The
Observer
:
public interface Observer { void notifyObservers(final Observable observable); }
The
Concrete Observer
:
public class Client implements Observer { private final String id; private Server server; public Client(final String id, final Server server) { this.id = id; setServer(server); } public String getId() { return id; } public Server getServer() { return server; } public void setServer(final Server server) { this.server = server; server.add(this); } public void notifyObservers(final Observable observable) { System.out.println("[Client '" + id + "'] Server '" + observable.getId() + "' - State: " + getServer().getState()); } }
The
Abstract Subject
:
public abstract class Observable { final List<Observer> observers = new ArrayList<>(); public void add(final Observer observer) { observers.add(observer); } public void remove(final Observer observer) { observers.remove(observer); } public void notifyObservers() { for (final Observer observer : observers) { observer.notifyObservers(this); } } public abstract String getId(); }
The
Concrete Subject
:
public class Server extends Observable { private final String id; private Boolean state; public Server(final String id, final Boolean state) { this.id = id; this.state = state; } public String getId() { return id; } public boolean getState() { return state; } public void setState(final boolean state) { this.state = state; notifyObservers(); } }
A simple class to test the
Observer
design pattern:
public class ObserverPatternTest { public static void main(String[] args) { final Server server1 = new Server("server1", Boolean.TRUE); final Client client1 = new Client("client1", server1); final Client client2 = new Client("client2", server1); // notify observers: client1, client2 System.out.println("-- Notify observers:"); server1.setState(Boolean.FALSE); // remove observer: client2 System.out.println("-- Remove observers: client2"); server1.remove(client2); // notify observers: client1 System.out.println("-- Notify observers:"); server1.setState(Boolean.TRUE); } }
© 2010-2022
mti
tek