设计模式-中介者模式

        中介者模式是一种行为设计模式,它通过将对象之间的交互委托给一个中介者对象来减少对象之间的直接耦合。中介者模式促进了对象之间的松耦合,并提供了一种集中式的方式来管理复杂的交互逻辑。

        在Java中实现中介者模式通常需要以下几个关键组件:

        1. 中介者接口(Mediator Interface):它是一个接口,定义了对象之间交互的方法。

        2. 具体中介者类(Concrete Mediator):它是中介者接口的具体实现,负责协调对象之间的交互。

        3. 同事类(Colleague):它是需要相互交互的对象。同事类通过中介者对象来进行交互,而不是直接与其他同事类交互。

        下面是一个简单的Java代码示例,演示了如何实现中介者模式:

// 中介者接口
interface Mediator {
    void sendMessage(String message, Colleague colleague);
}

// 具体中介者类
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;
    }

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

// 同事类
abstract class Colleague {
    protected Mediator mediator;

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

    public abstract void sendMessage(String message);

    public abstract void receiveMessage(String message);
}

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

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

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

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

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

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

// Usage
public class Main {
    public static void main(String[] args) {
        ConcreteMediator mediator = new ConcreteMediator();

        ConcreteColleague1 colleague1 = new ConcreteColleague1(mediator);
        ConcreteColleague2 colleague2 = new ConcreteColleague2(mediator);

        mediator.setColleague1(colleague1);
        mediator.setColleague2(colleague2);

        colleague1.sendMessage("Hello from Colleague1");
        colleague2.sendMessage("Hi from Colleague2");
    }
}

        在这个示例中,我们定义了一个简单的中介者模式,其中Mediator接口表示中介者,ConcreteMediator类表示具体中介者,Colleague类表示同事类。在Main类中,我们创建了一个中介者对象、两个同事对象,并演示了它们之间的交互。

你可能感兴趣的:(设计模式,1024程序员节)