本文主要是介绍Mediator 中介者,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
意图
使用一个中介者对象来封装一系列的对象交互。中介者使各个对象不需要显式地互相引用,从而使其耦合松散,而且可以独立的改变他们之间的交互。
结构
- Mediator(中介者)定义一个接口用于各同事(Colleague)对象通信
- ConcreteMediator(具体中介者)通过协调各同事对象实现协作行为;了解并维护它的各个同事。
- Colleague class(同事类)知道它的中介者对象;每个同事类对象在需要与其他同事通信的时候与它的中介者通信。
适用性
- 一组对象以定义良好但是复杂的方式进行通信,产生的交互依赖结构混乱且难以理解。
- 一个对象引用其他很多对象并且直接与这些对象通信,导致难以复用该对象。
- 想定制一个分布在多个类的行为,而又不想生成太多的子类。
代码示例
// 抽象中介者
interface Mediator {void register(Colleague colleague);void sendMessage(String message, Colleague colleague);
}// 具体中介者
class ConcreteMediator implements Mediator {private Colleague colleagueA;private Colleague colleagueB;public void register(Colleague colleague) {if (colleague instanceof ColleagueA) {colleagueA = colleague;} else if (colleague instanceof ColleagueB) {colleagueB = colleague;}}public void sendMessage(String message, Colleague colleague) {if (colleague == colleagueA) {colleagueB.receiveMessage(message);} else if (colleague == colleagueB) {colleagueA.receiveMessage(message);}}
}// 抽象同事类
abstract class Colleague {protected Mediator mediator;public Colleague(Mediator mediator) {this.mediator = mediator;}public abstract void receiveMessage(String message);
}// 具体同事类 A
class ColleagueA extends Colleague {public ColleagueA(Mediator mediator) {super(mediator);mediator.register(this);}public void sendMessage(String message) {mediator.sendMessage(message, this);}@Overridepublic void receiveMessage(String message) {System.out.println("ColleagueA received message: " + message);}
}// 具体同事类 B
class ColleagueB extends Colleague {public ColleagueB(Mediator mediator) {super(mediator);mediator.register(this);}public void sendMessage(String message) {mediator.sendMessage(message, this);}@Overridepublic void receiveMessage(String message) {System.out.println("ColleagueB received message: " + message);}
}// 测试类
public class MediatorPatternDemo {public static void main(String[] args) {Mediator mediator = new ConcreteMediator();Colleague colleagueA = new ColleagueA(mediator);Colleague colleagueB = new ColleagueB(mediator);colleagueA.sendMessage("Hello, ColleagueB!");colleagueB.sendMessage("Hi, ColleagueA!");}
}
在这个例子中,ConcreteMediator
作为中介者,协调 ColleagueA
和 ColleagueB
的通信。当 ColleagueA
或 ColleagueB
需要与对方通信时,它们会通过 ConcreteMediator
发送消息。
这篇关于Mediator 中介者的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!