# Mediator Pattern in Java for Simplified Object Communication

<div><strong>Source</strong>: <a href='https://www.tuanh.net/blog/java/mediator-pattern-in-java-for-simplified-object-communication'>Mediator Pattern in Java for Simplified Object Communication</a></div><div class="line-post"> 
 <h2 class="title-post">1. What is the Mediator Pattern, and Why Does It Matter?</h2> 
</div>
<div class="line-post"> 
 <h3 class="sub1">1.1 Understanding the Core Concept</h3> 
</div>
<div class="line-post">
  The Mediator Pattern is a behavioral design pattern that allows objects to communicate through a central mediator rather than directly with each other. This helps to reduce the dependencies among classes and promotes loose coupling. By managing the communication through a mediator, the code becomes less complex, enhancing readability and maintainability. 
</div>
<div class="line-post"> 
 <h3 class="sub1">1.2 The Advantages of Using the Mediator Pattern</h3> 
</div>
<div class="line-post">
  When applied correctly, the Mediator Pattern can: 
</div>
<div class="line-post"> 
 <ul> 
  <li><strong>Simplify Communication Logic</strong>: With all interactions routed through a central mediator, modifying how objects communicate becomes simpler.</li> 
  <li><strong>Enhance Scalability</strong>: By removing direct dependencies between objects, you can easily add or remove components.</li> 
  <li><strong>Promote Code Reusability</strong>: Decoupled components are more reusable since they don’t rely on specific interactions with other components.</li> 
 </ul> 
</div>
<div class="line-post"> 
 <h3 class="sub1">1.3 Use Cases in Java Applications</h3> 
</div>
<div class="line-post">
  It’s especially useful in scenarios such as GUI applications, chat applications, and transaction systems where numerous objects interact. 
</div>
<div class="line-post"> <strong>Example</strong>: In a chat room, users send messages to a mediator (chat server) that relays messages to the appropriate users. Each user doesn’t need to know the details of the communication process, only how to send messages to the server. 
</div>
<div class="line-post"> 
 <h2 class="title-post">2. Implementing the Mediator Pattern in Java: A Step-by-Step Guide</h2> 
</div>
<div class="line-post">
  Let’s build a practical example of a chat room where users can communicate through a central ChatMediator. This example will clarify the roles of different components within the Mediator Pattern and showcase best practices. 
</div>
<div class="line-post"> 
 <h3 class="sub1">2.1 Defining the Core Components</h3> 
</div>
<div class="line-post"> <strong>Mediator Interface</strong>: Outlines the methods for communication. 
</div>
<div class="line-post"> <strong>Concrete Mediator</strong>: Implements the mediator interface and handles communication among User objects. 
</div>
<div class="line-post"> <strong>Colleague Interface</strong>: Represents the participants (users). 
</div>
<div class="line-post"> <strong>Concrete Colleagues</strong>: Users who communicate through the mediator. 
</div>
<div class="line-post"> 
 <h3 class="sub1">2.2 Building the Mediator Interface and ConcreteMediator Class</h3> 
</div>
<pre class="code"><span class="keyword-css">interface</span> ChatMediator {<br>    <span class="keyword-css">void</span> sendMessage(String message, User user);<br>    <span class="keyword-css">void</span> addUser(User user);<br>}<br><br><span class="keyword-css">class</span> ChatMediatorImpl <span class="keyword-css">implements</span> ChatMediator {<br>    <span class="keyword-css">private</span> List&lt;User&gt; users = <span class="keyword-css">new</span> ArrayList&lt;&gt;();<br><br>    @Override<br>    <span class="keyword-css">public</span> <span class="keyword-css">void</span> addUser(User user) {<br>        <span class="keyword-css">this</span>.users.add(user);<br>    }<br><br>    @Override<br>    <span class="keyword-css">public</span> <span class="keyword-css">void</span> sendMessage(String message, User sender) {<br>        <span class="keyword-css">for</span> (User user : users) {<br>            <span class="keyword-css">if</span> (user != sender) {<br>                user.receive(message);<br>            }<br>        }<br>    }<br>}</pre>
<div class="line-post"> <strong>Explanation</strong>: Here, ChatMediatorImpl manages a list of users and defines the logic for message passing. The sendMessage method checks that the sender does not receive their own message, which is sent to other users only. 
</div>
<div class="line-post"> 
 <h3 class="sub1">2.3 Implementing the User (Colleague) Class</h3> 
</div>
<pre class="code"><span class="keyword-css">abstract</span> <span class="keyword-css">class</span> User {<br>    <span class="keyword-css">protected</span> ChatMediator mediator;<br>    <span class="keyword-css">protected</span> String name;<br><br>    <span class="keyword-css">public</span> User(ChatMediator mediator, String name) {<br>        <span class="keyword-css">this</span>.mediator = mediator;<br>        <span class="keyword-css">this</span>.name = name;<br>    }<br><br>    <span class="keyword-css">public</span> <span class="keyword-css">abstract</span> <span class="keyword-css">void</span> send(String message);<br>    <span class="keyword-css">public</span> <span class="keyword-css">abstract</span> <span class="keyword-css">void</span> receive(String message);<br>}<br><br><span class="keyword-css">class</span> UserImpl <span class="keyword-css">extends</span> User {<br>    <span class="keyword-css">public</span> UserImpl(ChatMediator mediator, String name) {<br>        <span class="keyword-css">super</span>(mediator, name);<br>    }<br><br>    @Override<br>    <span class="keyword-css">public</span> <span class="keyword-css">void</span> send(String message) {<br>        System.out.println(<span class="keyword-css">this</span>.name + " sends: " + message);<br>        mediator.sendMessage(message, <span class="keyword-css">this</span>);<br>    }<br><br>    @Override<br>    <span class="keyword-css">public</span> <span class="keyword-css">void</span> receive(String message) {<br>        System.out.println(<span class="keyword-css">this</span>.name + " receives: " + message);<br>    }<br>}</pre>
<div class="line-post"> <strong>Explanation</strong>: In the UserImpl class, we have the send method, which sends a message to the mediator, and a receive method, which outputs the received message to the console. This setup effectively decouples users from one another; they only interact with the ChatMediator. 
</div>
<div class="line-post"> 
 <h3 class="sub1">2.4 Testing the Mediator Pattern in Action</h3> 
</div>
<pre class="code"><span class="keyword-css">public</span> <span class="keyword-css">class</span> MediatorPatternExample {<br>    <span class="keyword-css">public</span> <span class="keyword-css">static</span> <span class="keyword-css">void</span> main(String[] args) {<br>        ChatMediator chatMediator = <span class="keyword-css">new</span> ChatMediatorImpl();<br>        <br>        User user1 = <span class="keyword-css">new</span> UserImpl(chatMediator, "Alice");<br>        User user2 = <span class="keyword-css">new</span> UserImpl(chatMediator, "Bob");<br>        User user3 = <span class="keyword-css">new</span> UserImpl(chatMediator, "Charlie");<br><br>        chatMediator.addUser(user1);<br>        chatMediator.addUser(user2);<br>        chatMediator.addUser(user3);<br><br>        user1.send("Hello, everyone!");<br>    }<br>}</pre>
<div class="line-post"> <strong>Explanation</strong>: This main method demonstrates how Alice sends a message that’s broadcast to Bob and Charlie through the mediator. No direct dependencies exist between users, showcasing the simplicity and flexibility introduced by the Mediator Pattern. 
</div>
<div class="line-post"> 
 <h2 class="title-post">3. Best Practices for Using the Mediator Pattern in Java</h2> 
</div>
<div class="line-post"> 
 <h3 class="sub1">3.1 Start Simple with a Focused Mediator</h3> 
</div>
<div class="line-post">
  It’s best to start with a mediator that only manages the interactions it needs to. Overloading the mediator can turn it into a “god object,” which defeats the pattern’s purpose of reducing complexity. 
</div>
<div class="line-post"> 
 <h3 class="sub1">3.2 Favor Composition over Inheritance</h3> 
</div>
<div class="line-post">
  Using interfaces and composition makes the code more flexible and aligns with the principles of clean code design. 
</div>
<div class="line-post"> 
 <h2 class="title-post">4. Potential Challenges and How to Address Them</h2> 
</div>
<div class="line-post"> <strong>Performance Overhead</strong> 
</div>
<div class="line-post">
  In high-performance systems, using a mediator can add latency due to the extra layer of communication. This is often a trade-off for the improved maintainability and should be carefully evaluated. 
</div>
<div class="line-post"> <strong>Testing Complexity</strong> 
</div>
<div class="line-post">
  While the pattern simplifies communication, testing can become challenging as you must ensure all interactions function correctly. Employing unit tests for the mediator itself can help verify correct behavior across all components. 
</div>
<div class="line-post"> 
 <h2 class="title-post">5. Conclusion</h2> 
</div>
<div class="line-post">
  The Mediator Pattern can transform how objects interact, leading to cleaner, more modular code. With the right approach, it can simplify your communication flows and enhance your code’s scalability. Are there any particular challenges you’ve faced with implementing design patterns? Feel free to leave a comment below, and let’s discuss! 
</div><p><strong>Read more at </strong>: <a href='https://www.tuanh.net/blog/java/mediator-pattern-in-java-for-simplified-object-communication'>Mediator Pattern in Java for Simplified Object Communication</a></p>
