您的位置:首页 > 健康 > 养生 > 为什么南极建站在2月_网页游戏用什么开发_深圳市seo上词多少钱_网站建设seo

为什么南极建站在2月_网页游戏用什么开发_深圳市seo上词多少钱_网站建设seo

2024/10/5 22:03:58 来源:https://blog.csdn.net/yanwenwennihao/article/details/142640628  浏览:    关键词:为什么南极建站在2月_网页游戏用什么开发_深圳市seo上词多少钱_网站建设seo
为什么南极建站在2月_网页游戏用什么开发_深圳市seo上词多少钱_网站建设seo

定义

中介者模式(Mediator Pattern)是一种行为设计模式,通过引入一个中介者对象,来降低多个对象之间的直接交互,从而减少它们之间的耦合度。中介者充当不同对象之间的协调者,使得对象之间的通信变得简单且集中。

UML图

在这里插入图片描述

  • Mediator(中介者接口):定义中介者与同事之间的交互方法。
  • ConcreteMediator(具体中介者):实现中介者接口,维护对同事对象的引用,并协调它们之间的交互。
  • Colleague(同事抽象类):通常持有对中介者的引用,通过中介者进行通信。
  • ConcreteColleague(同事类):具体的组件类,通常持有对中介者的引用,通过中介者进行通信。

代码

// Mediator interface
interface Mediator {void send(String message, Colleague colleague);
}// Concrete Mediator
class ChatMediator implements Mediator {private List<Colleague> colleagues = new ArrayList<>();public void addColleague(Colleague colleague) {colleagues.add(colleague);}@Overridepublic void send(String message, Colleague colleague) {for (Colleague c : colleagues) {// Prevent sending message back to the senderif (c != colleague) {c.receive(message);}}}
}// Colleague interface
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);
}// Concrete Colleague
class User extends Colleague {private String name;public User(Mediator mediator, String name) {super(mediator);this.name = name;}@Overridepublic void send(String message) {System.out.println(name + ": Sending message: " + message);mediator.send(message, this);}@Overridepublic void receive(String message) {System.out.println(name + ": Received message: " + message);}
}// Client code
public class MediatorPatternDemo {public static void main(String[] args) {ChatMediator mediator = new ChatMediator();User user1 = new User(mediator, "Alice");User user2 = new User(mediator, "Bob");mediator.addColleague(user1);mediator.addColleague(user2);user1.send("Hello Bob!");user2.send("Hi Alice!");}
}

优点

  • 降低耦合性:同事对象不需要直接引用彼此,减少了依赖关系。
  • 集中管理:所有的交互逻辑集中在中介者中,易于维护和修改。
  • 灵活性:可以方便地添加新的同事类或修改交互逻辑,而不需要改变其他类。

缺点

  • 中介者复杂性:中介者可能会变得复杂,尤其是当它需要处理多个同事对象时。
  • 扩展困难:添加新的同事类可能需要对中介者进行修改,从而影响系统的灵活性。

使用场景

  • 当多个对象之间的通信需要被集中控制时。
  • 当系统中存在大量同事对象,且它们之间的交互复杂时。
  • 当希望减少类之间的依赖关系,提升系统的可维护性时。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com