温馨提示×

中介者模式在Java中如何应用

小樊
83
2024-08-18 21:57:41
栏目: 编程语言

中介者模式是一种行为设计模式,它通过将对象之间的通信集中到一个中介者对象中来减少对象之间的直接依赖关系。在Java中,中介者模式经常用于实现复杂的交互系统,例如图形用户界面框架或多人游戏中的通信系统。

在Java中,可以通过定义一个中介者接口和实现类来实现中介者模式。首先,定义一个中介者接口,其中包含用于对象之间通信的方法:

public interface Mediator {
    void sendMessage(String message, Colleague colleague);
}

然后,创建具体的中介者实现类,实现中介者接口的方法:

public class ConcreteMediator implements Mediator {
    private Colleague colleague1;
    private Colleague colleague2;

    public void setColleague1(Colleague colleague1) {
        this.colleague1 = colleague1;
    }

    public void setColleague2(Colleague colleague2) {
        this.colleague2 = colleague2;
    }

    @Override
    public void sendMessage(String message, Colleague colleague) {
        if (colleague == colleague1) {
            colleague2.receiveMessage(message);
        } else if (colleague == colleague2) {
            colleague1.receiveMessage(message);
        }
    }
}

接下来,定义同事类,同事类可以向中介者发送消息并接收来自中介者的消息:

public abstract class Colleague {
    protected Mediator mediator;

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

    public void sendMessage(String message) {
        mediator.sendMessage(message, this);
    }

    public abstract void receiveMessage(String message);
}

最后,创建具体的同事类,实现同事类的抽象方法:

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

    @Override
    public void receiveMessage(String message) {
        System.out.println("ConcreteColleague1 received message: " + message);
    }
}

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

    @Override
    public void receiveMessage(String message) {
        System.out.println("ConcreteColleague2 received message: " + message);
    }
}

通过以上的代码示例,可以实现一个简单的中介者模式。在实际应用中,中介者模式可以帮助管理对象之间复杂的交互关系,降低耦合度,使系统更易于维护和扩展。

0