Agent SkillsPatternsDev/skills › mediator-pattern

mediator-pattern

GitHub

讲解中介者模式,用于解决多组件间直接通信导致的复杂耦合问题。通过中央中介者协调请求转发,实现解耦。适用于中间件链、聊天室等场景,指导创建中心化处理逻辑。

javascript/mediator-pattern/SKILL.md PatternsDev/skills

Trigger Scenarios

需要简化多组件间的通信逻辑 存在复杂的直接依赖关系 实现中间件或消息中转机制

Install

npx skills add PatternsDev/skills --skill mediator-pattern -g -y
More Options

Non-standard path

npx skills add https://github.com/PatternsDev/skills/tree/main/javascript/mediator-pattern -g -y

Use without installing

npx skills use PatternsDev/skills@mediator-pattern

指定 Agent (Claude Code)

npx skills add PatternsDev/skills --skill mediator-pattern -a claude-code -g -y

安装 repo 全部 skill

npx skills add PatternsDev/skills --all -g -y

预览 repo 内 skill

npx skills add PatternsDev/skills --list

SKILL.md

Frontmatter
{
    "name": "mediator-pattern",
    "paths": [
        "**\/*.js",
        "**\/*.ts"
    ],
    "license": "MIT",
    "metadata": {
        "author": "patterns.dev",
        "version": "1.1"
    },
    "description": "Teaches the mediator pattern for centralized component communication. Use when multiple components need to communicate and direct coupling between them creates complexity or tight dependencies.",
    "related_skills": [
        "module-pattern",
        "singleton-pattern"
    ]
}

Mediator/Middleware Pattern

The mediator pattern makes it possible for components to interact with each other through a central point: the mediator. Instead of directly talking to each other, the mediator receives the requests, and sends them forward! In JavaScript, the mediator is often nothing more than an object literal or a function.

You can compare this pattern to the relationship between an air traffic controller and a pilot. Instead of having the pilots talk to each other directly, which would probably end up being quite chaotic, the pilots talk the air traffic controller. The air traffic controller makes sure that all planes receive the information they need in order to fly safely, without hitting the other airplanes.

When to Use

  • Use this when multiple objects need to communicate but direct many-to-many relationships would be chaotic
  • This is helpful for implementing middleware chains (e.g., Express.js middleware)

When NOT to Use

  • When direct communication between two components is simpler and the system has few participants
  • When the mediator itself becomes a monolithic "god object" that's hard to maintain
  • When event-driven patterns (observer/pub-sub) provide sufficient decoupling without a central coordinator

Instructions

  • Create a central mediator that processes requests and forwards them to the appropriate handlers
  • Use the middleware pattern to chain processing functions that can modify requests/responses
  • Keep individual components unaware of each other; they only know about the mediator

Details

Although we're hopefully not controlling airplanes in JavaScript, we often have to deal with multidirectional data between objects. The communication between the components can get rather confusing if there is a large number of components.

Instead of letting every object talk directly to the other objects, resulting in a many-to-many relationship, the object's requests get handled by the mediator. The mediator processes this request, and sends it forward to where it needs to be.

A good use case for the mediator pattern is a chatroom! The users within the chatroom won't talk to each other directly. Instead, the chatroom serves as the mediator between the users.

class ChatRoom {
  logMessage(user, message) {
    const time = new Date();
    const sender = user.getName();

    console.log(`${time} [${sender}]: ${message}`);
  }
}

class User {
  constructor(name, chatroom) {
    this.name = name;
    this.chatroom = chatroom;
  }

  getName() {
    return this.name;
  }

  send(message) {
    this.chatroom.logMessage(this, message);
  }
}

We can create new users that are connected to the chat room. Each user instance has a send method which we can use in order to send messages.

Case Study

Express.js is a popular web application server framework. We can add callbacks to certain routes that the user can access.

Say we want add a header to the request if the user hits the root '/'. We can add this header in a middleware callback.

const app = require("express")();

app.use("/", (req, res, next) => {
  req.headers["test-header"] = 1234;
  next();
});

The next method calls the next callback in the request-response cycle. We'd effectively be creating a chain of middleware functions that sit between the request and the response, or vice versa.

Let's add another middleware function that checks whether the test-header was added correctly. The change added by the previous middleware function will be visible throughout the chain.

const app = require("express")();

app.use(
  "/",
  (req, res, next) => {
    req.headers["test-header"] = 1234;
    next();
  },
  (req, res, next) => {
    console.log(`Request has test header: ${!!req.headers["test-header"]}`);
    next();
  }
);

Perfect! We can track and modify the request object all the way to the response through one or multiple middleware functions.

Every time the user hits a root endpoint '/', the two middleware callbacks will be invoked.

The middleware pattern makes it easy for us to simplify many-to-many relationships between objects, by letting all communication flow through one central point.

Source

References

Version History

  • 48bf58a Current 2026-07-24 16:34

Same Skill Collection

javascript/bundle-splitting/SKILL.md
javascript/command-pattern/SKILL.md
javascript/compression/SKILL.md
javascript/dynamic-import/SKILL.md
javascript/factory-pattern/SKILL.md
javascript/flyweight-pattern/SKILL.md
javascript/import-on-interaction/SKILL.md
javascript/import-on-visibility/SKILL.md
javascript/islands-architecture/SKILL.md
javascript/js-performance-patterns/SKILL.md
javascript/loading-sequence/SKILL.md
javascript/mixin-pattern/SKILL.md
javascript/module-pattern/SKILL.md
javascript/observer-pattern/SKILL.md
javascript/prefetch/SKILL.md
javascript/preload/SKILL.md
javascript/prototype-pattern/SKILL.md
javascript/provider-pattern/SKILL.md
javascript/proxy-pattern/SKILL.md
javascript/prpl/SKILL.md
javascript/route-based/SKILL.md
javascript/singleton-pattern/SKILL.md
javascript/static-import/SKILL.md
javascript/third-party/SKILL.md
javascript/tree-shaking/SKILL.md
javascript/view-transitions/SKILL.md
javascript/virtual-lists/SKILL.md
javascript/vite-bundle-optimization/SKILL.md
react/ai-ui-patterns/SKILL.md
react/client-side-rendering/SKILL.md
react/compound-pattern/SKILL.md
react/hoc-pattern/SKILL.md
react/hooks-pattern/SKILL.md
react/incremental-static-rendering/SKILL.md
react/presentational-container-pattern/SKILL.md
react/progressive-hydration/SKILL.md
react/react-2026/SKILL.md
react/react-composition-2026/SKILL.md
react/react-data-fetching/SKILL.md
react/react-render-optimization/SKILL.md
react/react-selective-hydration/SKILL.md
react/react-server-components/SKILL.md
react/render-props-pattern/SKILL.md
react/server-side-rendering/SKILL.md
react/static-rendering/SKILL.md
react/streaming-ssr/SKILL.md
vue/async-components/SKILL.md
vue/components/SKILL.md
vue/composables/SKILL.md

Metadata

Files
0
Version
48bf58a
Hash
a2a6cfda
Indexed
2026-07-24 16:34

inicio - Wiki
Copyright © 2011-2026 iteam. Current version is 2.155.2. UTC+08:00, 2026-08-20 05:51
浙ICP备14020137号-1 $mapa de visitantes$