Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Mediator Pattern

1. Introduction

The Mediator Pattern defines an object that encapsulates how a set of objects interact. This pattern promotes loose coupling by keeping objects from referring to each other explicitly, and it allows a mediator to control the interactions between them.

2. Definition

The main purpose of the Mediator Pattern is to reduce the dependencies between communicating objects, hence facilitating easier maintenance and scalability in software design.

3. How It Works

The Mediator acts as a central hub for communication. Instead of objects communicating directly with each other, they notify the mediator when an event occurs. The mediator then informs the appropriate objects accordingly.

graph TD;
                A[Component A] -->|notify| B[Mediator]
                B --> C[Component B]
                B --> D[Component C]
                C -->|response| D
            

4. Implementation

Below is a basic implementation of the Mediator Pattern in Python:

class Mediator:
    def notify(self, sender, event):
        pass

class ConcreteMediator(Mediator):
    def __init__(self, component1, component2):
        self._component1 = component1
        self._component1.mediator = self
        self._component2 = component2
        self._component2.mediator = self

    def notify(self, sender, event):
        if event == "A":
            print("Mediator reacts on A's event")
            self._component2.do_something()
        elif event == "B":
            print("Mediator reacts on B's event")
            self._component1.do_something()

class Component1:
    def __init__(self):
        self.mediator = None

    def do_something(self):
        print("Component 1 does something")

class Component2:
    def __init__(self):
        self.mediator = None

    def do_something(self):
        print("Component 2 does something")

# Usage
component1 = Component1()
component2 = Component2()
mediator = ConcreteMediator(component1, component2)

component1.mediator.notify(component1, "A")
component2.mediator.notify(component2, "B")
                

5. Best Practices

  • Use the Mediator Pattern when you have a complex set of interactions between objects.
  • Maintain a single mediator to manage all interactions to reduce coupling.
  • Avoid overusing the Mediator Pattern, as it can lead to a god object that handles too many responsibilities.

6. FAQ

What are the advantages of using the Mediator Pattern?

The main advantage is reduced dependencies between components, promoting easier maintenance and flexibility.

When should I use the Mediator Pattern?

Use it when you need to centralize the communication between multiple components.

Can Mediator Pattern be used in UI development?

Yes, it's often used in UI frameworks to manage interactions between UI components.