Behavioural Design Pattern: Mediator Pattern - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

Behavioural Design Pattern: Mediator Pattern

Share This
The definition of a mediator pattern is "to define an object that encapsulates the interactions between a set of objects."

To elucidate the Mediator pattern, I shall contemplate a problem. At the outset of the development process, there are only a handful of classes, which produce results through their interactions. Let us now contemplate gradually how the complexity of the logic escalates as the functionality expands. What then happens? Even though we continue to add classes that interact with one another, this code has become extremely difficult to maintain. The Mediator pattern effectively resolves this issue.

The mediator pattern is employed to simplify the communication process among numerous classes or objects. This design pattern includes a mediator class that facilitates communication between classes and promotes code maintainability through the use of loose coupling.

The benefits are:
  • Decoupling occurs with regard to the quantity of classes. 
  • The process streamlines object protocols. 
  • Centralization of control occurs. 
  • When individual components are not required to exchange messages with one another, they become considerably more streamlined and manageable.  
 
As a result of not requiring logic to manage their intercommunication, the components are more generic.


It finds widespread applicability in message-based systems, including chat applications. When the interactions among the set of objects are intricate yet clearly delineated.

Source code of Machine.java
package com.t4b.test.java.dp.bp.mp; class Machine { private String name; public Machine(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void sendMessage(String message) { Printer.showMessage(this, message); } }
Source code of Printer.java
package com.t4b.test.java.dp.bp.mp; import java.util.Date; class Printer { public static void showMessage(Machine machine, String message) { System.out.println(new Date().toString() + " [" + machine.getName() + "] : " + message); } }
Source code of Main.java
package com.t4b.test.java.dp.bp.mp; class Main { public static void main(String[] args) { Machine machine1 = new Machine("Machine1"); Machine machine2 = new Machine("Machine2"); machine1.sendMessage("Rebooting"); machine2.sendMessage("Computing"); } }

Happy Exploring!

No comments:

Post a Comment