Java23种设计模式——中介者模式

该系列文章为博主学习笔记,原文请参考参考链接
本文禁止转载,但是欢迎大家留言区留言交流[微笑]

中介者模式特(面)点(试):又称调停者模式。如果系统中对象之间的联系呈现为网状结构,对象之间存在大量的多对多联系(一个对象里面引用了其他对象,而其他对象又被另外一些对象引用),可以采用中介者模式,将一个网状结构转换成为一个星形结构。通过引入中介者对象(维持了对各个组件对象的引用),使一个对象不在与另一个对象发生关联,而是通过中介者对象与另一个对象进行通信。

这里写图片描述

这里写图片描述
例题:
这里写图片描述

代码:

//抽象中介者
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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值