Home
Cloud
Big Data
CI
Install
Samples
Java
Ubuntu
Maven
Archive
Design Patterns
|
Mediator
References
Example
The
Subject
(1)
The
Subject
(2)
The
Mediator
The
Concrete Mediator
A simple class to test the
Mediator
design pattern
References
Definition: (
source:
http://en.wikipedia.org/wiki/Mediator_pattern
)
The Mediator pattern defines an object that encapsulates how a set of objects interact.
Class diagram: (
source:
http://en.wikipedia.org/wiki/Mediator_pattern
)
Example
The
Subject
(1):
public class Customer { private final String id; private final Mediator mediator; public Customer(final String id, final Mediator mediator) { this.id = id; this.mediator = mediator; mediator.add(this); } public String getId() { return id; } public void lookup(final String productId) { mediator.lookup(this, productId); } public void notify(final Supplier supplier, final String productId) { System.out.println("[Customer: " + id + "] Supplier '" + supplier.getId() + "' has the product: " + productId); } }
The
Subject
(2):
public class Supplier { private final String id; private final Mediator mediator; public Supplier(final String id, final Mediator mediator) { this.id = id; this.mediator = mediator; mediator.add(this); } public String getId() { return id; } public void notify(final String productId) { mediator.notify(this, productId); } public void lookup(final Customer customer, final String productId) { System.out.println("[Supplier: " + id + "] Customer '" + customer.getId() + "' looking for product: " + productId); } }
The
Mediator
:
public interface Mediator { void add(final Customer customer); void add(final Supplier supplier); void lookup(final Customer customer, final String productId); void notify(final Supplier supplier, final String productId); }
The
Concrete Mediator
:
public class MediatorImpl implements Mediator { List<Customer> customers = new ArrayList<Customer>(); List<Supplier> suppliers = new ArrayList<Supplier>(); public void add(final Customer customer) { customers.add(customer); } public void add(final Supplier supplier) { suppliers.add(supplier); } public void lookup(final Customer customer, final String productId) { for (Supplier supplier : suppliers) { supplier.lookup(customer, productId); } } public void notify(final Supplier supplier, final String productId) { for (Customer customer : customers) { customer.notify(supplier, productId); } } }
A simple class to test the
Mediator
design pattern:
public class MediatorPatternTest { public static void main(String[] args) { final Mediator mediator = new MediatorImpl(); final Customer customer = new Customer("customer1", mediator); final Supplier supplier = new Supplier("supplier1", mediator); final String productId = "1"; customer.lookup(productId); supplier.notify(productId); } }
© 2010-2022
mti
tek