Mediator y Chain of Responsibility
Explore dos patrones de comportamiento que desacoplan a los emisores de los receptores: Mediator centraliza la comunicación y Chain of Responsibility transmite las solicitudes a través de una cadena de handlers.
Mediator y Chain of Responsibility es una lección gratuita de Clean Architecture & Design Patterns in Practice en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Clean Architecture & Design Patterns in Practice, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Clean Architecture & Design Patterns in Practice incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Two Ways to Decouple Communication
Objects often need to talk to each other, but direct references create tangled webs of dependencies.
This lesson covers two behavioral solutions:
- Mediator routes all communication through a central hub.
- Chain of Responsibility passes a request down a line until someone handles it.
The Mediator Problem
Imagine a dialog with buttons, checkboxes, and text fields all reacting to each other. If every widget references every other widget, the coupling explodes.
Mediator replaces this mesh with a star: each widget talks only to the mediator.
Mediator Interface
The mediator defines how components notify it of events.
interface Mediator {
void notify(Component sender, String event);
}Concrete Mediator
The concrete mediator contains the coordination logic that used to be scattered.
class Dialog implements Mediator {
Button submit;
Checkbox terms;
public void notify(Component sender, String event) {
if (sender == terms && event.equals("toggle")) {
submit.setEnabled(terms.isChecked());
}
}
}Components Stay Dumb
Each component simply reports events to the mediator and reacts to instructions. It does not know about its siblings.
class Checkbox {
Mediator mediator;
boolean checked;
void toggle() {
checked = !checked;
mediator.notify(this, "toggle");
}
boolean isChecked() { return checked; }
}When to Use Mediator
- Components are tightly interconnected.
- Reuse is hard because objects depend on many others.
- Behavior is spread across classes and hard to change.
Beware: the mediator itself can grow into a god object if overloaded.
The Chain of Responsibility Problem
Now a different scenario: a request might be handled by one of several processors, and you do not want the sender to know which.
Examples: middleware pipelines, event bubbling, approval workflows.
Handler Interface
Each handler can process a request or pass it to the next handler.
abstract class Handler {
protected Handler next;
Handler setNext(Handler n) { this.next = n; return n; }
abstract void handle(Request r);
}A Concrete Handler
A handler decides whether it can deal with the request; otherwise it forwards.
class AuthHandler extends Handler {
void handle(Request r) {
if (!r.authenticated) {
System.out.println("Rejected: not authenticated");
return;
}
if (next != null) next.handle(r);
}
}Building and Running the Chain
Handlers are linked, then the request enters at the head.
class Request { boolean authenticated = true; }
abstract class H { H next; H link(H n){next=n;return n;} abstract void handle(Request r); }
class Log extends H { void handle(Request r){ System.out.println("logged"); if(next!=null) next.handle(r);} }
class Done extends H { void handle(Request r){ System.out.println("handled"); } }
public class Main {
public static void main(String[] a){
H head = new Log();
head.link(new Done());
head.handle(new Request());
}
}Comparing the Two
- Mediator: many-to-many coordination through one hub; bidirectional.
- Chain: a one-directional pipeline; each link is independent and order matters.
Both decouple senders from receivers, but solve different shapes of problem.
Quick Check
Test your understanding of these two patterns.
Recap
You learned two communication-decoupling patterns.
- Mediator turns a mesh of dependencies into a star around a coordinator.
- Chain of Responsibility forwards a request along independent handlers until one handles it.
Preguntas frecuentes
¿La lección «Mediator y Chain of Responsibility» es gratis?
Sí — el texto completo de «Mediator y Chain of Responsibility» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Clean Architecture & Design Patterns in Practice, actualiza a CoddyKit PRO. El curso de Clean Architecture & Design Patterns in Practice incluye 4 lecciones en total.
¿Qué aprenderé en «Mediator y Chain of Responsibility»?
Explore dos patrones de comportamiento que desacoplan a los emisores de los receptores: Mediator centraliza la comunicación y Chain of Responsibility transmite las solicitudes a través de una cadena… Practicas Clean Architecture & Design Patterns in Practice con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Clean Architecture & Design Patterns in Practice?
No se requiere experiencia previa. Clean Architecture & Design Patterns in Practice en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Mediator y Chain of Responsibility»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Clean Architecture & Design Patterns in Practice?
Sí. Cada lección de Clean Architecture & Design Patterns in Practice incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Patrones Observer y Strategy
- Patrones Command e Iterator
- Patrones Template Method y State
- Mediator y Chain of Responsibility