Observer
Observer
For our observer pattern java program example, we would implement a simple
topic and observers can register to this topic. Whenever any new message
will be posted to the topic, all the registers observers will be notified and they
can consume the message.
Based on the requirements of Subject, here is the base Subject interface that
defines the contract methods to be implemented by any concrete subject.
Next we will create contract for Observer, there will be a method to attach the
Subject to the observer and another method to be used by Subject to notify of
any change.
Now our contract is ready, let’s proceed with the concrete implementation of
our topic.
import java.util.ArrayList;
import java.util.List;
public MyTopic(){
this.observers=new ArrayList<>();
}
@Override
public void register(Observer obj) {
if(obj == null) throw new
NullPointerException("Null Observer");
synchronized (MUTEX) {
if(!observers.contains(obj)) observers.add(obj);
}
}
@Override
public void unregister(Observer obj) {
synchronized (MUTEX) {
observers.remove(obj);
}
}
@Override
public void notifyObservers() {
List<Observer> observersLocal = null;
//synchronization is used to make sure any observer
registered after message is received is not notified
synchronized (MUTEX) {
if (!changed)
return;
observersLocal = new
ArrayList<>(this.observers);
this.changed=false;
}
for (Observer obj : observersLocal) {
obj.update();
}
@Override
public Object getUpdate(Observer obj) {
return this.message;
}
@Override
public void setSubject(Subject sub) {
this.topic=sub;
}
//create observers
Observer obj1 = new MyTopicSubscriber("Obj1");
Observer obj2 = new MyTopicSubscriber("Obj2");
Observer obj3 = new MyTopicSubscriber("Obj3");
That’s all for Observer design pattern in java, I hope you liked it. Share your
love with comments and by sharing it with others.