Mediator Design Pattern: Bringing Harmony to the Code Ensemble

Ever felt like you're the mediator at a lively dinner party, ensuring everyone communicates smoothly? Well, the Mediator Design Pattern plays a similar role in the world of code. It's a behavioral pattern that helps objects communicate without directly referencing each other, promoting a more organized and less chaotic system.

Concept:

  • Mediator: Defines an interface for communication between colleagues.
  • ConcreteMediator: Implements the Mediator interface and manages the communication between colleagues.
  • Colleague: Defines an interface for communication with other colleagues.
  • ConcreteColleague: Implements the Colleague interface and communicates through the Mediator.
  • Client: Initiates communication by interacting with colleagues.

Example:

Let's imagine a chatroom where users can send messages to each other, and the Mediator ensures that messages reach the right recipient without the senders knowing who the receivers are.

Mediator Interface:

# Mediator Interface
class ChatMediator
  def send_message(message, sender)
    raise NotImplementedError, 'Subclasses must implement the send_message method'
  end
end

ConcreteMediator:

# ConcreteMediator
class ChatRoom < ChatMediator
  def initialize
    @users = []
  end

  def add_user(user)
    @users << user
  end

  def send_message(message, sender)
    @users.each do |user|
      user.receive_message(message) unless user == sender
    end
  end
end

Colleague Interface:

# Colleague Interface
class User
  attr_reader :name, :chat_mediator

  def initialize(name, chat_mediator)
    @name = name
    @chat_mediator = chat_mediator
  end

  def send_message(message)
    @chat_mediator.send_message(message, self)
  end

  def receive_message(message)
    puts "#{name} received message: #{message}"
  end
end

ConcreteColleagues:

# ConcreteColleagues
alice = User.new('Alice', chat_room)
bob = User.new('Bob', chat_room)
charlie = User.new('Charlie', chat_room)

chat_room.add_user(alice)
chat_room.add_user(bob)
chat_room.add_user(charlie)

alice.send_message("Hi, everyone! What's up?")
# Outputs:
# Bob received message: Hi, everyone! What's up?
# Charlie received message: Hi, everyone! What's up?

In this chatty example:

  • ChatMediator is the mediator interface defining a method for sending messages.
  • ChatRoom is the concrete mediator managing communication between users.
  • User is the colleague interface providing a method for sending messages.
  • Users like Alice, Bob, and Charlie are concrete colleagues communicating through the mediator.

So, imagine the code as a lively chatroom, with the Mediator (chat room) ensuring that messages travel seamlessly between colleagues (users). It keeps the communication organized and prevents a cacophony of direct interactions. Just like at a great party, everyone can communicate without chaos!