DESIGN PATTERNS SAGA #12: REAL PROJECT SITUATIONS WITH MEDIATOR

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 for 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).

DESIGN PATTERNS SAGA #12: REAL PROJECT SITUATIONS WITH MEDIATOR

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s