Implement Mediator in Java by moving coordination rules into one explicit collaborator instead of spreading them across peer objects.
Mediator: A pattern that centralizes interaction rules between collaborating objects so peers do not need to know as much about one another directly.
A typical Java mediator owns the workflow between colleagues:
1public interface BookingMediator {
2 void roomSelected(String roomId);
3 void paymentConfirmed(String reservationId);
4}
1public final class DefaultBookingMediator implements BookingMediator {
2 private final RoomSelection selection;
3 private final PaymentPanel payment;
4 private final ConfirmationView confirmation;
5
6 public DefaultBookingMediator(
7 RoomSelection selection,
8 PaymentPanel payment,
9 ConfirmationView confirmation) {
10 this.selection = selection;
11 this.payment = payment;
12 this.confirmation = confirmation;
13 }
14
15 @Override
16 public void roomSelected(String roomId) {
17 payment.enableFor(roomId);
18 }
19
20 @Override
21 public void paymentConfirmed(String reservationId) {
22 confirmation.show(reservationId);
23 }
24}
The components no longer need to know each other directly. They only report to the mediator.
Mediator is useful when coordination logic is otherwise distributed across many peers and becomes hard to follow.
If the mediator owns every business rule, every dependency, and every workflow, it stops being a focused collaboration hub and becomes a god service.