Clean Architecture & Design Patterns in Practice · Lezione

Mediator e Chain of Responsibility

Esplori due pattern comportamentali che disaccoppiano mittenti e destinatari: Mediator centralizza la comunicazione, mentre Chain of Responsibility inoltra le richieste lungo una catena di handler.

Lezione 4 di 413 passaggi

Mediator e Chain of Responsibility è una lezione Clean Architecture & Design Patterns in Practice gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Clean Architecture & Design Patterns in Practice, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Clean Architecture & Design Patterns in Practice include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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.
Gratis per iniziare

Impara Clean Architecture & Design Patterns in Practice con un tutor IA — gratis

Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.

Corsi
12
Lezioni
48

Domande Frequenti

La lezione «Mediator e Chain of Responsibility» è gratuita?

Sì — il testo completo di «Mediator e Chain of Responsibility» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Clean Architecture & Design Patterns in Practice, passa a CoddyKit PRO. Il corso Clean Architecture & Design Patterns in Practice include 4 lezioni in totale.

Cosa imparerò in «Mediator e Chain of Responsibility»?

Esplori due pattern comportamentali che disaccoppiano mittenti e destinatari: Mediator centralizza la comunicazione, mentre Chain of Responsibility inoltra le richieste lungo una catena di handler. Eserciti Clean Architecture & Design Patterns in Practice con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Clean Architecture & Design Patterns in Practice?

Non è richiesta alcuna esperienza precedente. Clean Architecture & Design Patterns in Practice su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Mediator e Chain of Responsibility»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Clean Architecture & Design Patterns in Practice?

Sì. Ogni lezione Clean Architecture & Design Patterns in Practice include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Pattern Observer e Strategy
  2. Pattern Command e Iterator
  3. Pattern Template Method e State
  4. Mediator e Chain of Responsibility
← Torna a Clean Architecture & Design Patterns in Practice