Observer Pattern
Pub-sub pattern, basically register the subscriber to the publisher.
package designpatterns.observer;
import java.util.UUID;
public class Subscriber {
private String id;
private NotificationService notificationService;
public Subscriber(NotificationService notificationService) {
this.notificationService = notificationService;
this.id = UUID.randomUUID().toString();
}
public void notifySubscriber() {
System.out.println("I'm notified id: " + id);
}
public void subscribe() {
notificationService.subscribe(this);
}
public void unSubscribe() {
notificationService.unSubscribe(this);
}
}
package designpatterns.observer;
import java.util.HashSet;
import java.util.Set;
public class NotificationService {
private final Set<Subscriber> subscribers;
public NotificationService() {
subscribers = new HashSet<>();
}
public void subscribe(Subscriber subscriber) {
subscribers.add(subscriber);
}
public void unSubscribe(Subscriber subscriber) {
subscribers.remove(subscriber);
}
public void notifyAllSubscriber() {
subscribers.forEach(Subscriber::notifySubscriber);
}
}
package designpatterns.observer.test;
import designpatterns.observer.NotificationService;
import designpatterns.observer.Subscriber;
import org.junit.jupiter.api.Test;
class NotificationServiceTest {
@Test
void endToEnd_givenNotificationService_shouldSubscribeUser() {
NotificationService notificationService = new NotificationService();
Subscriber subscriber = new Subscriber(notificationService);
Subscriber subscriber1 = new Subscriber(notificationService);
Subscriber subscriber2 = new Subscriber(notificationService);
Subscriber subscriber3 = new Subscriber(notificationService);
subscriber.subscribe();
subscriber2.subscribe();
subscriber3.subscribe();
subscriber.unSubscribe();
notificationService.notifyAllSubscriber();
}
}