Java23种设计模式——中介者模式
来源:互联网 发布:软件安全性设计 编辑:程序博客网 时间:2024/06/03 07:44
该系列文章为博主学习笔记,原文请参考参考链接
本文禁止转载,但是欢迎大家留言区留言交流[微笑]
中介者模式特(面)点(试):又称调停者模式。如果系统中对象之间的联系呈现为网状结构,对象之间存在大量的多对多联系(一个对象里面引用了其他对象,而其他对象又被另外一些对象引用),可以采用中介者模式,将一个网状结构转换成为一个星形结构。通过引入中介者对象(维持了对各个组件对象的引用),使一个对象不在与另一个对象发生关联,而是通过中介者对象与另一个对象进行通信。
例题:
代码:
//抽象中介者abstract class Mediator { public abstract void mediator(Pane c);}
//具体中介者class Windows extends Mediator { public TextPane textPane; public ListPane listPane; public GraphicPane graphicPane; @Override public void mediator(Pane c) { if (c==textPane){ System.out.println("用户点击了TextPane,--ListPane,GraphicPane--进行显示"); listPane.diaplay(); graphicPane.diaplay(); }else if (c==listPane){ System.out.println("用户点击了ListPane,--TextPane,GraphicPane--进行显示"); textPane.diaplay(); graphicPane.diaplay(); }else { System.out.println("用户点击了GraphicPane,--TextPane,ListPane--进行显示"); textPane.diaplay(); listPane.diaplay(); } }}
//抽象组件类public abstract class Pane { private Mediator mediator; public void setMediator(Mediator mediator) { this.mediator = mediator; } public void show(){ this.mediator.mediator(this); } public abstract void diaplay();}
//具体组件类public class TextPane extends Pane{ @Override public void diaplay() { System.out.println("显示TextPane"); }}
//具体组件类public class GraphicPane extends Pane { @Override public void diaplay() { System.out.println("显示GraphicPane"); }}
//具体组件类public class ListPane extends Pane{ @Override public void diaplay() { System.out.println("显示ListPane"); }}
public class MyClass { public static void main(String[] args){ Windows windows=new Windows(); TextPane textPane=new TextPane(); ListPane listPane=new ListPane(); GraphicPane graphicPane=new GraphicPane(); textPane.setMediator(windows); listPane.setMediator(windows); graphicPane.setMediator(windows); windows.listPane=listPane; windows.textPane=textPane; windows.graphicPane=graphicPane; textPane.show(); System.out.println("——————————————"); graphicPane.show(); }}
输出:
中介者模式的核心是在中介者类中包含了所有具体组件对象的引用,避免了一个组件对象与另外一个组件对象直接耦合,中介者类就相当于星形结构中间的星,当两个具体组件对象通信时,先与中介者类进行通讯,再由中介者类完成与另一个组件对象通信。
对于新增加的具体组件对象(如ButtonPane),可以直接编写ButtonPane继承抽象组件类Pane,然后编写一个新的具体中介类,继承Windows,增加ButtonPane类的引用,并重写mediator()方法,最后在客户端中将Windows类改为新增加的具体中介类即可。
微信公众号:
QQ交流群:365473065
阅读全文
0 0
- Java23种设计模式——中介者模式
- java23种设计模式(3)-中介者模式
- Java23种设计模式——建造者模式
- Java23种设计模式——Iterator设计模式
- 设计模式——中介者模式
- 设计模式——中介者模式
- 设计模式——中介者模式
- 设计模式——中介者模式
- 设计模式——中介者模式
- 设计模式—Mediator中介者模式
- 大话设计模式—中介者模式
- Java设计模式—中介者模式
- Java23种设计模式
- JAVA23种设计模式
- JAVA23种设计模式
- JAVA23种设计模式
- JAVA23种设计模式
- JAVA23种设计模式
- Async和Await异步编程的原理
- [网络流 24 题] 方格取数问题 骑士共存问题
- 7.3
- Windows平台PE文件,内存地址到磁盘地址的转换(RVA to RAW),破解补丁原理
- 亚马逊欧洲站对灯串有什么要求?灯串没EN60598-2-20标准报告会被下架?
- Java23种设计模式——中介者模式
- 带参数的装饰器
- android——高效调用系统图库
- insert /*+append*/
- react-router
- 树莓派编译FFMPEG
- 关于shrio在web校验权限时你所要知道的
- 环境搭建-CentOS集群搭建
- Oracle中trunc函数、round 函数、ceil函数和floor函数的使用