The mediator pattern of Java design patterns is one of the behavioral patterns. Define a mediating object to encapsulate the interaction between series objects. Mediators remove the need for objects to explicitly reference each other, making them loosely coupled and allowing them to independently change their interactions.
As shown below:
Examples of intermediary models between producers, consumers, and agents:
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"); }}
Running results:
hello! i am a consumerI am a producer