欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

Java设计模式之中介者模式(Mediator Pattern)简介

时间:2020-11-29 10:27:55|栏目:JAVA代码|点击:

Java设计模式的中介者模式是行为模式之一。定义一个中介对象来封装系列对象之间的交互。中介者使各个对象不需要显式地相互引用,从而使其耦合性松散,并且可以独立地改变他们之间的交互。

如下图所示:

生产者、消费者、代理商之间的中介模式实例:

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

上一篇:java文件上传下载功能实现代码

栏    目:JAVA代码

下一篇:使用Maven搭建Hadoop开发环境

本文标题:Java设计模式之中介者模式(Mediator Pattern)简介

本文地址:http://www.codeinn.net/misctech/27397.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有