The observer pattern is a pattern for working with state changes. A subject notifies a list of observers that something has changed.
Mostly related toOOP (object-oriented programming), where it translates to the following: Objects subscribe to events, which happen to other objects.
An example in Java, using objects, which shows the benefit of using this pattern. Using subscribers, the VideoChannel doesn’t have to loop over all accounts - instead, it directly knows its subscribers.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
// "Observer"
class Subscriber {
private final String name;
public Subscriber(String name) {
this.name = name;
}
public void update(String channelName, String videoTitle) {
System.out.printf("👀 %s New upload on: %s -> \"%s\"%n",
name, channelName, videoTitle);
}
@Override
public String toString() {
return name;
}
}
// "Subject" (Observable)
class VideoChannel {
private final String name;
private final List<Subscriber> subscribers = new ArrayList<>();
public VideoChannel(String name) {
this.name = name;
}
// Register an observer
public void subscribe(Subscriber s) {
if (s == null) return;
if (!subscribers.contains(s)) {
subscribers.add(s);
System.out.printf("✅ %s hat %s abonniert.%n", s, name);
}
}
// Unsubscribe an observer
public void unsubscribe(Subscriber s) {
if (subscribers.remove(s)) {
System.out.printf("🚪 %s hat %s deabonniert.%n", s, name);
}
}
public void notify(String videoTitle) {
List<Subscriber> snapshot = Collections.unmodifiableList(new ArrayList<>(subscribers));
for (Subscriber s : snapshot) {
s.update(name, videoTitle);
}
}
public void uploadVideo(String title) {
System.out.printf("📢 %s lädt ein neues Video hoch: \"%s\"%n", name, title);
notify(title);
}
}
// Kleine Demo
public class ObserverPatternDemo {
public static void main(String[] args) {
VideoChannel channel = new VideoChannel("DevCoffee");
Subscriber alice = new Subscriber("Alice");
Subscriber bob = new Subscriber("Bob");
Subscriber carl = new Subscriber("Carl");
channel.subscribe(alice);
channel.subscribe(bob);
channel.subscribe(carl);
channel.uploadVideo("Observer Pattern in 10 Minuten");
channel.unsubscribe(bob);
channel.uploadVideo("SOLID-Prinzipien einfach erklärt");
}
}