程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA編程入門知識 >> Java設計模式之中介者模式(Mediator Pattern)簡介

Java設計模式之中介者模式(Mediator Pattern)簡介

編輯: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
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved