java设计模式之中介者模式

中介者模式(Mediator Pattern)

基本介绍

  1. 中介者模式,用一个中介对象来封装一系列的对象交互。中介者使各个对象不需要显式地相互引用,从而使其解耦松散。而且可以独立地改变它们之间的交互。
  2. 中介者模式属于行为型模式。
  3. 比如MVC模式,Controller控制器是Model和View视图的中介者,再前后端交互时起到了中间人的作用。

原理类图

原理

Mediator: 就是抽象中介者,定义了同事对象到中介者对象的接口。
Colleague: 是抽象同事类。
ConcreteMediator: 具体的中介者对象,实现抽象方法,他需要知道所有的具体同事类,即以一个集合来管理HashMap,并接收某个同事对象消息,完成相应的任务。
ConcreteColleague: 具体的同事类,会有很多,每个同事只知道自己行为,而不了解其他同事类的行为,但是他们都依赖中介者对象。

应用实例

  1. 智能家庭包括各种设备,闹钟,咖啡机,电视机,窗帘等。
  2. 要看电视时,各个设备可以协同工作,自动完成看电视的准备工作,比如流程是:闹铃响起,咖啡机开始做咖啡,窗帘自动落下,电视机开始播放。

思路分析类图:
类图
代码如下:

//同事抽象类
public abstract class Colleague {private Mediator mediator;public String name;public Colleague(Mediator mediator, String name) {this.mediator = mediator;this.name = name;}public Mediator GetMediator() {return this.mediator;}public abstract void SendMessage(int stateChange);
}public abstract class Mediator {//将给中介者对象,加入到集合中public abstract void Register(String colleagueName, Colleague colleague);//接收消息, 具体的同事对象发出public abstract void GetMessage(int stateChange, String colleagueName);public abstract void SendMessage();
}//具体的中介者类
public class ConcreteMediator extends Mediator {//集合,放入所有的同事对象private HashMap<String, Colleague> colleagueMap;private HashMap<String, String> interMap;public ConcreteMediator() {colleagueMap = new HashMap<String, Colleague>();interMap = new HashMap<String, String>();}@Overridepublic void Register(String colleagueName, Colleague colleague) {// TODO Auto-generated method stubcolleagueMap.put(colleagueName, colleague);// TODO Auto-generated method stubif (colleague instanceof Alarm) {interMap.put("Alarm", colleagueName);} else if (colleague instanceof CoffeeMachine) {interMap.put("CoffeeMachine", colleagueName);} else if (colleague instanceof TV) {interMap.put("TV", colleagueName);} else if (colleague instanceof Curtains) {interMap.put("Curtains", colleagueName);}}//具体中介者的核心方法//1. 根据得到消息,完成对应任务//2. 中介者在这个方法,协调各个具体的同事对象,完成任务@Overridepublic void GetMessage(int stateChange, String colleagueName) {// TODO Auto-generated method stub//处理闹钟发出的消息if (colleagueMap.get(colleagueName) instanceof Alarm) {if (stateChange == 0) {((CoffeeMachine) (colleagueMap.get(interMap.get("CoffeeMachine")))).StartCoffee();((TV) (colleagueMap.get(interMap.get("TV")))).StartTv();} else if (stateChange == 1) {((TV) (colleagueMap.get(interMap.get("TV")))).StopTv();}} else if (colleagueMap.get(colleagueName) instanceof CoffeeMachine) {((Curtains) (colleagueMap.get(interMap.get("Curtains")))).UpCurtains();} else if (colleagueMap.get(colleagueName) instanceof TV) {//如果TV发现消息} else if (colleagueMap.get(colleagueName) instanceof Curtains) {//如果是以窗帘发出的消息,这里处理...}}@Overridepublic void SendMessage() {// TODO Auto-generated method stub}
}//具体的同事类
public class Alarm extends Colleague {//构造器public Alarm(Mediator mediator, String name) {super(mediator, name);// TODO Auto-generated constructor stub//在创建Alarm 同事对象时,将自己放入到ConcreteMediator 对象中[集合]mediator.Register(name, this);}public void SendAlarm(int stateChange) {SendMessage(stateChange);}@Overridepublic void SendMessage(int stateChange) {// TODO Auto-generated method stub//调用的中介者对象的getMessagethis.GetMediator().GetMessage(stateChange, this.name);}
}public class CoffeeMachine extends Colleague {public CoffeeMachine(Mediator mediator, String name) {super(mediator, name);// TODO Auto-generated constructor stubmediator.Register(name, this);}@Overridepublic void SendMessage(int stateChange) {// TODO Auto-generated method stubthis.GetMediator().GetMessage(stateChange, this.name);}public void StartCoffee() {System.out.println("It's time to startcoffee!");}public void FinishCoffee() {System.out.println("After 5 minutes!");System.out.println("Coffee is ok!");SendMessage(0);}
}public class Curtains extends Colleague {public Curtains(Mediator mediator, String name) {super(mediator, name);// TODO Auto-generated constructor stubmediator.Register(name, this);}@Overridepublic void SendMessage(int stateChange) {// TODO Auto-generated method stubthis.GetMediator().GetMessage(stateChange, this.name);}public void UpCurtains() {System.out.println("I am holding Up Curtains!");}
}public class TV extends Colleague {public TV(Mediator mediator, String name) {super(mediator, name);// TODO Auto-generated constructor stubmediator.Register(name, this);}@Overridepublic void SendMessage(int stateChange) {// TODO Auto-generated method stubthis.GetMediator().GetMessage(stateChange, this.name);}public void StartTv() {// TODO Auto-generated method stubSystem.out.println("It's time to StartTv!");}public void StopTv() {// TODO Auto-generated method stubSystem.out.println("StopTv!");}
}public static void main(String[] args) {//创建一个中介者对象Mediator mediator = new ConcreteMediator();//创建Alarm 并且加入到  ConcreteMediator 对象的HashMapAlarm alarm = new Alarm(mediator, "alarm");//创建了CoffeeMachine 对象,并  且加入到  ConcreteMediator 对象的HashMapCoffeeMachine coffeeMachine = new CoffeeMachine(mediator,"coffeeMachine");//创建 Curtains , 并  且加入到  ConcreteMediator 对象的HashMapCurtains curtains = new Curtains(mediator, "curtains");TV tV = new TV(mediator, "TV");//让闹钟发出消息alarm.SendAlarm(0);coffeeMachine.FinishCoffee();alarm.SendAlarm(1);}

运行结果:
结果

注意细节

  1. 多个类相互耦合,会形成网状结构,使用中介者模式将网状结构分离成星型结构,进行解耦。
  2. 减少类间依赖,降低了耦合,符合迪米特原则。
  3. 中介者承担了较多的责任,一旦中介者出现了问题,整个系统就会受到影响。
  4. 如果设计不当,中介者对象本身变得过于复杂,这点在使用时,特别注意。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/462869.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

动漫风博客介绍页面源码

动漫风博客介绍页面源码&#xff0c;HTML源码&#xff0c;图片背景有淡入切换特效 蓝奏云&#xff1a;https://wfr.lanzout.com/iIDZu1nrmjve

Python 小白的 Leetcode Daily Challenge 刷题计划 - 20240209(除夕)

368. Largest Divisible Subset 难度&#xff1a;Medium 动态规划 方案还原 Yesterdays Daily Challenge can be reduced to the problem of shortest path in an unweighted graph while todays daily challenge can be reduced to the problem of longest path in an unwe…

SparkJDBC读写数据库实战

默认的操作 代码val df = spark.read.format("jdbc").option("url", "jdbc:postgresql://localhost:5432/testdb").option("user", "username").option("password", "password").option("driver&q…

基于鲲鹏服务器的LNMP配置

基于鲲鹏服务器的LNMP配置 系统 Centos8 # cat /etc/redhat-release CentOS Linux release 8.0.1905 (Core) 卸载已经存在的旧版本的安装包 # rpm -qa | grep php #查看已经安装的PHP旧版本# rpm -qa | grep php | xargs rpm -e #卸载已经安装的旧版&#xff0c;如果提示有…

在面试中如何回复擅长vue还是react

当面试官问及这个问题的时候&#xff0c;我们需要思考面试官是否是在乎你是掌握vue还是react吗&#xff1f;&#xff1f;&#xff1f; 在大前端的一个环境下&#xff0c;当前又有AI人工智能的加持辅助&#xff0c;我们是不是要去思考企业在进行前端岗位人员需求的时候&#xf…

阿里云幻兽帕鲁服务器免费搭建解决方法,白嫖阿里云

阿里云幻兽帕鲁服务器免费搭建方案&#xff0c;先在阿里云高校计划「云工开物」活动领取学生专享300元无门槛代金券&#xff0c;幻兽帕鲁专用服务器4核16G配置26元1个月、149元半年&#xff0c;直接使用这个无门槛300元代金券抵扣即可免费搭建幻兽帕鲁服务器。阿里云服务器网al…

产品效果图为何要用渲染100农场?渲染100邀请码1a12

产品效果图很重要&#xff0c;它能帮助设计人员和消费者理解产品特点&#xff0c;是不可或缺的一步。产品效果图渲染耗时耗力&#xff0c;不仅慢而且容易出错&#xff0c;在这种情况下&#xff0c;使用渲染农场就成了必备选择&#xff0c;以目前国内最好的渲染农场渲染100为例&…

C++进阶(十三)异常

&#x1f4d8;北尘_&#xff1a;个人主页 &#x1f30e;个人专栏:《Linux操作系统》《经典算法试题 》《C》 《数据结构与算法》 ☀️走在路上&#xff0c;不忘来时的初心 文章目录 一、C语言传统的处理错误的方式二、C异常概念三、异常的使用1、异常的抛出和捕获2、异常的重新…

LabVIEW工业监控系统

LabVIEW工业监控系统 介绍了一个基于LabVIEW软件开发的工业监控系统。系统通过虚拟测控技术和先进的数据处理能力&#xff0c;实现对工业过程的高效监控&#xff0c;提升系统的自动化和智能化水平&#xff0c;从而满足现代工业对高效率、高稳定性和低成本的需求。 随着工业自…

视觉开发板—K210自学笔记(二)

视觉开发板—K210 一、开发之前的准备 工欲善其事必先利其器。各位同学先下载下面的手册&#xff1a; 1.Sipeed-Maix-Bit 资料下载&#xff1a;https://dl.sipeed.com/shareURL/MAIX/HDK/Sipeed-Maix-Bit/Maix-Bit_V2.0_with_MEMS_microphone 2.Sipeed-Maix-Bit 规格书下载&…

C++自幂数判断<GESP C++ 二级>

题目&#xff1a; 代码&#xff1a; #include <iostream> using namespace std; int main() {int m 0;cin >> m;for (int i 0; i < m; i) {int n 0;cin >> n;// 数一下 n 有多少位数&#xff0c;记为 lint t n, l 0;while (t > 0) {t / 10;l;}/…

【web前端开发】HTML及CSS简单页面布局练习

案例一 网页课程 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><meta http-equiv"X-UA-Compatible" content"IEedge"><meta name"viewport" content"widthdevice-wi…