IT职涯

一个多年的IT人的博客
随笔 - 33, 文章 - 0, 评论 - 189, 阅读 - 18万
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

Java设计模式十二: 中介者模式(Mediator Pattern)

Posted on   IT职涯  阅读(1963)  评论(0编辑  收藏  举报

中介者模式是行为模式之一。定义一个中介对象来封装系列对象之间的交互。中介者使各个对象不需要显示地相互引用,从而使其耦合性松散

,而且可以独立地改变他们之间的交互。

类图:



实例:生产者、消费者、代理商
public abstract class PersonColleague
{
    protected Mediator mediator;

    public Mediator getMediator()
    {
        return mediator;
    }

    public void setMediator(final Mediator mediator)
    {
        this.mediator = mediator;
    }

    protected abstract void message(String context);

}

public class Mediator
{
    private PersonColleague consumer = null;
    private ProducerColleague producer = null;

    public ProducerColleague getProducer()
    {
        return producer;
    }

    public void setProducer(final ProducerColleague producer)
    {
        this.producer = producer;
    }

    public PersonColleague getConsumer()
    {
        return consumer;
    }

    public void setConsumer(final PersonColleague consumer)
    {
        this.consumer = consumer;
    }

    public Mediator()
    {
    }

    public synchronized void message(final String context)
    {
        if (consumer != null)
        {
            System.out.println(context);
        }
        else if (producer != null)
        {
            System.out.println(context);
        }
    }
}

public class ConsumerColleague extends PersonColleague
{
    public ConsumerColleague(final Mediator mediator)
    {
        this.mediator = mediator;
    }

    @Override
    protected void message(final String context)
    {
        this.mediator.setConsumer(this);
        this.mediator.message("hello! i am a consumer");
    }
}

public class ProducerColleague extends PersonColleague
{
    public ProducerColleague(final Mediator mediator)
    {
        this.mediator = mediator;
    }

    @Override
    protected void message(final String context)
    {
        this.mediator.setProducer(this);
        this.mediator.message(context);
    }
}

public class Client
{
    public static void main(final String[] args)
    {
        final Mediator mediator = new Mediator();
        final PersonColleague person = new ConsumerColleague(mediator);
        final PersonColleague person1 = new ProducerColleague(mediator);

        person.message("I am a consumer");
        person1.message("I am a producer");
    }
}

结果:
hello! i am a consumer
I am a producer

编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示