Problem

Designing reusable components generally results in the "spaghetti code" phenomenon. Dependencies between pieces tend towards all or nothing.

Solution

Represent the interactions between objects in a system with a Mediator object. The many-to-many relationships between peers is promoted to "full object status".

Related Patterns

Discussion

Colleagues (or peers) do not interact with each other directly. Instead, they speak with the Mediator, which knows and conducts the others. It's important to note that not all interacting objects would benefit from mutual decoupling, however it can be useful to abstract those interactions into a new class.

Examples

The Mediator pattern could be useful in the design of a user and group permissions system in an operating system. If a group can have zero or more users, and a user can be a member of zero or more groups, the Mediator pattern provides a flexible approach to mapping and managing users and groups.

An Air Traffic Control center at a busy airport represents the Mediator in a real-world situation. Instead of each airplane talking to all the others, they only speak with the control tower. Since the tower has knowledge of where all other planes are, they can best direct planes individually on when to take off and land.

Code

Rather than having a Node keep track of its own next Node and pointers, abstract that away into a List Mediator. This handles things like deleting the head Node.

class Node{
private:
  int value;
public:
  Node(int v){value = v;}
  int get_val(){return value;}
}

class List{
private:
  vector list;
  public:
  add_node(Node *n){list.push(n);}
  add_node(int v){list.push(new Node(v));}
  void traverse(){
    for(int i = 0; i < list.size(); i++) cout << list[i]->get_val();
    cout << endl;
  }
  void remove_node(int v){
    for(vector::iterator iter = list.begin(); iter != list.end(); ++iter){
      if((*iter)->get_val() == v){
        list.erase(iter);
        break;
      }
    }
  }
}