中介者模式

行为型模式

中介者模式

中介者模式(Mediator Pattern)是用来降低多个对象和类之间的通信复杂性。这种模式提供了一个中介类,该类通常处理不同类之间的通信,并支持松耦合,使代码易于维护

优点

缺点

使用场景

示例

public class MediatorPattern {

    public static void main(String[] args) {
        concreteMediator cm = new concreteMediator();
        ColleagueA a = new ColleagueA("tom", cm);
        ColleagueB b = new ColleagueB("jerry", cm);
        cm.setA(a);
        cm.setB(b);
        a.contact("i have something to b");
        b.contact("i busy!! don't intterupt me");
    }
}

abstract class Mediator {
    public abstract void contact(String content, Colleague coll);
}

class concreteMediator extends Mediator {
    ColleagueA a;
    ColleagueB b;

    public ColleagueA getA() {
        return a;
    }

    public void setA(ColleagueA a) {
        this.a = a;
    }

    public ColleagueB getB() {
        return b;
    }

    public void setB(ColleagueB b) {
        this.b = b;
    }

    @Override
    public void contact(String content, Colleague coll) {
        if (coll == a) {
            b.getMes(content);
        } else {
            a.getMes(content);
        }
    }
}


class ColleagueA extends Colleague {
    public ColleagueA(String name, Mediator mediator) {
        super(name, mediator);
    }

    public void getMes(String mes) {
        System.out.println("collA " + name + "get mes " + mes);
    }

    public void contact(String mes) {
        mediator.contact(mes, this);
    }
}

class ColleagueB extends Colleague {
    public ColleagueB(String name, Mediator mediator) {
        super(name, mediator);
    }

    public void getMes(String mes) {
        System.out.println("collB " + name + "get mes " + mes);
    }

    public void contact(String mes) {
        mediator.contact(mes, this);
    }
}

class Colleague {
    protected String name;
    protected Mediator mediator;

    public Colleague(String name, Mediator mediator) {
        this.name = name;
        this.mediator = mediator;
    }
}