设计模式-中介者模式(二)

2023-05-04 15:48:01 浏览数 (1)

定义抽象同事类

代码语言:javascript复制
public abstract class Colleague {
    protected Mediator mediator;

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

    public abstract void send(String message);

    public abstract void receive(String message);
}

定义具体同事类

代码语言:javascript复制
public class ColleagueSales extends Colleague {
    public ColleagueSales(Mediator mediator) {
        super(mediator);
    }

    @Override
    public void send(String message) {
        mediator.send(message, this);
    }

    @Override
    public void receive(String message) {
        System.out.println("Sales department receives message: "   message);
    }
}

public class ColleagueFinance extends Colleague {
    public ColleagueFinance(Mediator mediator) {
        super(mediator);
    }

    @Override
    public void send(String message) {
        mediator.send(message, this);
    }

    @Override
    public void receive(String message) {
        System.out.println("Finance department receives message: "   message);
    }
}

public class ColleagueMarket extends Colleague {
    public ColleagueMarket(Mediator mediator) {
        super(mediator);
    }

    @Override
    public void send(String message) {
        mediator.send(message, this);
    }

    @Override
    public void receive(String message) {
        System.out.println("Market department receives message: "   message);
    }
}

0 人点赞