El patrón de diseño del mediador se utiliza para colaborar con un conjunto de colegas. Esos colegas no se comunican entre sí directamente, sino a través del mediador.
En el siguiente ejemplo, el colega A quiere hablar y el colega B quiere pelear. Cuando realizan alguna acción (es decir, hacer algo ()), invocan al mediador para que lo haga.
Diagrama de clases de mediador
Código Java de mediador
package designpatterns.mediator; interface IMediator { public void fight(); public void talk(); public void registerA(ColleagueA a); public void registerB(ColleagueB a); } //concrete mediator class ConcreteMediator implements IMediator{ ColleagueA talk; ColleagueB fight; public void registerA(ColleagueA a){ talk = a; } public void registerB(ColleagueB b){ fight = b; } public void fight(){ System.out.println("Mediator is fighting"); //let the fight colleague do some stuff } public void talk(){ System.out.println("Mediator is talking"); //let the talk colleague do some stuff } } abstract class Colleague { IMediator mediator; public abstract void doSomething(); } //concrete colleague class ColleagueA extends Colleague { public ColleagueA(IMediator mediator) { this.mediator = mediator; } @Override public void doSomething() { this.mediator.talk(); this.mediator.registerA(this); } } //concrete colleague class ColleagueB extends Colleague { public ColleagueB(IMediator mediator) { this.mediator = mediator; this.mediator.registerB(this); } @Override public void doSomething() { this.mediator.fight(); } } public class MediatorTest { public static void main(String[] args) { IMediator mediator = new ConcreteMediator(); ColleagueA talkColleague = new ColleagueA(mediator); ColleagueB fightColleague = new ColleagueB(mediator); talkColleague.doSomething(); fightColleague.doSomething(); } } |
Entre otros patrones de comportamiento, Observer es el patrón más similar con Mediator. Puede leer el patrón Observer para comparar la diferencia.