javascript技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript技巧 > JS中介者模式

JS设计模式之中介者模式使用方法详解

作者:慕仲卿

JavaScript中介者模式是一种行为型设计模式,用于降低多个对象之间的耦合性,在中介者模式中,多个对象之间不直接相互通信,而是通过中介者进行通信, 本文就来给大家详细的介绍一下JS设计模式之中介者模式使用方法,需要的朋友可以参考下

中介者模式(Mediator Pattern)

定义:

是一种行为型设计模式,用于降低多个对象之间的耦合性。

作用:

中介者模式通过引入一个中介者对象,将对象之间的交互集中管理和控制。

特点:

在中介者模式中,多个对象之间不直接相互通信,而是通过中介者进行通信。 中介者对象封装了对象之间的交互逻辑,各个对象只需要与中介者进行通信,而不需要了解其他对象的存在。

参与者:

工作流程:

优势:

劣势:

举例:

假设我们有一个简单的聊天室应用程序,其中包含多个用户对象和一个中介者对象来协调用户之间的通信。每个用户对象都可以发送消息给其他用户,并接收其他用户发送的消息

首先,定义抽象中介者接口:

abstract class AbstractMediator {
  // 通信用抽象方法
  abstract sendMessage(sender: Colleague, message: string): void;
}

然后,定义具体中介者类:

class ChatRoomMediator extends AbstractMediator {
  users = [];
  // 中介者收集同事类实例对象
  addUser(user: Colleague) {
    this.users.push(user);
  }
  // 实现通信用的抽象方法
  sendMessage(sender: Colleague, message: string) {
    for (let user of this.users) {
      user !== sender && user.receiveMessage(sender, message);
    }
  }
}

接下来,定义抽象同事类接口:

abstract class Colleague {
  constructor(public mediator: AbstractMediator) {}
  // 作为中介者模式的参与者,每一个同事类对象都具有发送信息和处理信息的方法
  // 不同之处在于发送信息方法已经被抽象类实现,而处理信息的方法需要根据子类的情况定制实现
  send(message) {
    this.mediator.sendMessage(this, message);
  }
  abstract receiveMessage(sender: Colleague, message: string): void;
}

然后,定义具体同事类:

class User extends Colleague {
  constructor(public name: string, mediator: AbstractMediator) {super(mediator)}
  receiveMessage(sender: Colleague, message: string) {
    console.log(`${this.name} received a message from ${sender.name}: ${message}`);
  }
}

最后,在客户端代码中创建中介者对象、同事对象; 使用中介者对象收集参与对话的同事对象并进行通信示例:

// 创建中介者对象
const chatRoomMediator = new ChatRoomMediator();
// 创建同事对象
// 每一个同事类对象都应该保持对中介者对象的引用
const user1 = new User('User 1', chatRoomMediator);
const user2 = new User('User 2', chatRoomMediator);
const user3 = new User('User 3', chatRoomMediator);
// 中介者对象收集同事类对象;其实这里也可以做成new User的时候自动将实例添加到中介者users数组中去,将具体同事类的构造函数修改成:
/*
  constructor(name: string, mediator: AbstractMediator) {
    super(mediator);
    this.name = name;
    mediator.addUser(this);
  }
*/
chatRoomMediator.addUser(user1);
chatRoomMediator.addUser(user2);
chatRoomMediator.addUser(user3);
// 用户之间通过中介者进行通信的示例
user1.send('Hello, everyone!');
user2.send('Hi, User 1!');
user3.send('Nice to meet you all!');
/*
>>>
User 2 received a message from User 1: Hello, everyone!
User 3 received a message from User 1: Hello, everyone!
User 1 received a message from User 2: Hi, User 1!
User 3 received a message from User 2: Hi, User 1!
User 1 received a message from User 3: Nice to meet you all!
User 2 received a message from User 3: Nice to meet you all!
*/

其他应用场景:

ws的客户端和服务端

以下是一个简单的示例代码,演示了WebSocket客户端和服务端之间的通信:

客户端代码:

const socket = new WebSocket('ws://localhost:8080');
socket.onopen = () => {
  console.log('WebSocket connection opened.');
  socket.send('Hello, server!');
};
socket.onmessage = (event) => {
  const message = event.data;
  console.log('Received message from server:', message);
};
socket.onclose = () => {
  console.log('WebSocket connection closed.');
};

服务端代码:

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', (ws) => {
  console.log('WebSocket connection established.');
  ws.on('message', (message) => {
    console.log('Received message from client:', message);
    ws.send('Hello, client!');
  });
  ws.on('close', () => {
    console.log('WebSocket connection closed.');
  });
});

electron的主进程和渲染进程

以下是一个简单的示例代码,演示了 Electron 主进程和渲染进程之间的通信:

主进程代码:

const { app, BrowserWindow, ipcMain } = require('electron');
let mainWindow;
app.on('ready', () => {
  mainWindow = new BrowserWindow();
  mainWindow.loadURL('index.html');
});
ipcMain.on('messageFromRenderer', (event, message) => {
  console.log('Received message from renderer:', message);
  event.sender.send('messageToRenderer', 'Hello, renderer!');
});

渲染进程代码(index.html):

<!DOCTYPE html>
<html>
  <body>
    <script>
      const { ipcRenderer } = require('electron');
      ipcRenderer.send('messageFromRenderer', 'Hello, main process!');
      ipcRenderer.on('messageToRenderer', (event, message) => {
        console.log('Received message from main process:', message);
      });
    </script>
  </body>
</html>

计算机主板硬件之间的关系

如下图所示:

+---------------------+
|      Mainboard      |
+---------------------+
|       Processor     |
|        Memory       |
|        GPU          |
|        ...          |
+---------------------+
         |
         |   +---------+
         +---|  Bus    |
             +---------+

业务使用场景:

class Mediator {
  constructor() {
    this.subscribers = [];
  }
  subscribe(subscriber) {
    this.subscribers.push(subscriber);
  }
  unsubscribe(subscriber) {
    this.subscribers = this.subscribers.filter((s) => s !== subscriber);
  }
  broadcast(event, data) {
    for (let subscriber of this.subscribers) {
      subscriber.handleEvent(event, data);
    }
  }
}
class Subscriber {
  handleEvent(event, data) {
    console.log(`Received event '${event}' with data:`, data);
  }
}
const mediator = new Mediator();
const subscriber1 = new Subscriber();
mediator.subscribe(subscriber1);
const subscriber2 = new Subscriber();
mediator.subscribe(subscriber2);
mediator.broadcast('click', { x: 100, y: 200 });
class Mediator {
  constructor() {
    this.fields = {};
  }
  registerField(field, validationRules, errorHandle) {
    this.fields[field] = { validationRules, errorHandle };
  }
  validate() {
    let isValid = true;
    for (let field in this.fields) {
      const { validationRules, errorHandle } = this.fields[field];
      const value = document.getElementById(field).value;
      for (let rule of validationRules) {
        if (!rule.test(value)) {
          errorHandle(field);
          isValid = false;
          break;
        }
      }
    }
    return isValid;
  }
}
const mediator = new Mediator();
mediator.registerField(
  'username',
  [/.{5,}/],
  (field) => console.log(`Invalid value for field '${field}'.`)
);
mediator.registerField(
  'password',
  [/.{8,}/, /[A-Z]/, /[0-9]/],
  (field) => console.log(`Invalid value for field '${field}'.`)
);
document.getElementById('submit-button').addEventListener('click', () => {
  if (mediator.validate()) {
    console.log('Form submitted successfully.');
  }
});

总结:

中介者模式提供了一种可扩展和可维护的方式来处理复杂的交互关系,适用于以下情况:

以上就是JS设计模式之中介者模式使用方法详解的详细内容,更多关于JS中介者模式的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文