Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Mediator Pattern (UI)

1. Introduction

The Mediator Pattern is a behavioral design pattern that allows objects to communicate with each other without knowing about each other's internal workings. This pattern promotes loose coupling in software design, making it easier to maintain and extend the functionality of the application.

2. Key Concepts

2.1 What is a Mediator?

A mediator is an object that encapsulates how a set of objects interact. By using a mediator, the objects can communicate with each other through the mediator instead of connecting directly.

2.2 Benefits of Using the Mediator Pattern

  • Reduces dependencies between components.
  • Encourages a centralized control structure, making it easier to manage complex interactions.
  • Facilitates the addition of new components without requiring changes to existing code.

3. Implementation

The following example illustrates how to implement the Mediator Pattern in a UI context, particularly for a chat application.


class Mediator {
    constructor() {
        this.users = {};
    }

    register(user) {
        this.users[user.name] = user;
        user.setMediator(this);
    }

    send(message, from, to) {
        if (to in this.users) {
            this.users[to].receive(message, from);
        }
    }
}

class User {
    constructor(name) {
        this.name = name;
        this.mediator = null;
    }

    setMediator(mediator) {
        this.mediator = mediator;
    }

    send(message, to) {
        console.log(`${this.name} sends: ${message}`);
        this.mediator.send(message, this.name, to);
    }

    receive(message, from) {
        console.log(`${this.name} received: ${message} from ${from}`);
    }
}

// Usage
const mediator = new Mediator();
const user1 = new User('Alice');
const user2 = new User('Bob');
mediator.register(user1);
mediator.register(user2);

user1.send('Hello Bob!', 'Bob');
user2.send('Hi Alice!', 'Alice');
        

4. Best Practices

  • Use the Mediator Pattern when you find that your objects are becoming tightly coupled.
  • Keep the mediator's responsibilities focused and avoid adding too much functionality to it.
  • Document interactions clearly to ensure maintainability.

5. FAQ

What are the main advantages of the Mediator Pattern?

The main advantages include reduced coupling, easier maintenance, and the ability to introduce new components without altering existing ones.

When should I not use the Mediator Pattern?

Avoid using the Mediator Pattern if the communication between components is simple and the overhead of the mediator does not justify its use.

Can the Mediator Pattern be used in any programming language?

Yes, the Mediator Pattern is a design pattern that can be implemented in any object-oriented programming language.