Mediator Design Pattern with Java

Mediator Design Pattern
Mediator Design Pattern

What should be done when we need to use a functionality that may be repeated in several classes? Should we repeat the code in all the classes? If the behavior of this functionality changes, you will be obligated to change it in the entire project and test everything. This would not be cool. Fortunately, there is a solution to this problem – we can use the Mediator Pattern!

Using the Mediator Pattern can encapsulate this behavior inside just one class allowing us to reuse this method in every necessary class. Doing this will result in cohesive code with low coupling.

mediator_diagram.PNG

Get the Design_Patterns_Saga_GitHub_Source_Code

1 – Mediator: This class will be responsible to mediate the necessary behavior of calculating the Discount. This pattern is pretty straightforward, it simply mediates functionality.

public class DiscountCalculatorMediator {

  private BigDecimal productValue;

  private BigDecimal DISCOUNT_RATE = new BigDecimal("0.10");

  public DiscountCalculatorMediator(BigDecimal productValue) {
    this.productValue = productValue;
  }

  public BigDecimal calculate() {
    return productValue.
        subtract(productValue.multiply(DISCOUNT_RATE));
  }
}

2 – Product POJO: We are going to mediate the calculateDiscount method to the Mediator class, and therefore we are not going to have the same code in different parts of the system. We will have this code only in the Mediator.

public class Product {

  private BigDecimal productValue;

  public Product(BigDecimal productValue) {
    this.productValue = productValue;
  }

  public BigDecimal calculateDiscount() {
    return new DiscountCalculatorMediator
        (productValue).calculate();
  }
}

Summary of actions:

  1. Created the Mediator class.
  2. Created the calculateDiscount behavior inside the Mediator.
  3. Reused the Mediator in the POJO.

To practice the Mediator Pattern you can create another Mediator class where you encapsulate a specific behavior and just reuse it in a method. Create another test method to make sure it works. Be sure to use TDD (Test Driven Development).

Written by
Rafael del Nero
Join the discussion

1 comment