search
HomeWeb Front-endJS TutorialJavaScript Mediator Pattern (Detailed Tutorial)

JavaScript Mediator Pattern (Detailed Tutorial)

Jun 07, 2018 pm 05:10 PM
javascriptDesign Patterns

这篇文章主要介绍了JavaScript设计模式之调停者模式,详细分析了调停者模式的概念、原理、优缺点并结合javascript实例形式给出了相关使用技巧,需要的朋友可以参考下

本文实例讲述了JavaScript设计模式之调停者模式。分享给大家供大家参考,具体如下:

1、定义

调停者模式包装了一系列对象相互作用的方式,使得这些对象不必相互明显作用。从而使他们可以松散偶合。当某些对象之间的作用发生改变时,不会立即影响其他的一些对象之间的作用。保证这些作用可以彼此独立的变化。调停者模式将多对多的相互作用转化为一对多的相互作用。调停者模式将对象的行为和协作抽象化,把对象在小尺度的行为上与其他对象的相互作用分开处理。

2、使用的原因

当对象之间的交互操作很多,且每个对象的行为操作都依赖彼此时,为防止在修改一个对象的行为时,同时涉及到修改很多其他对象的行为,可采用调停者模式,来解决紧耦合问题.

该模式将对象之间的多对多关系变成一对多关系,调停者对象将系统从网状结构变成以调停者为中心的星形结构,达到降低系统的复杂性,提高可扩展性的作用.

调停者设计模式结构图:

调停者模式包括以下角色:

●抽象调停者(Mediator)角色:定义出同事对象到调停者对象的接口,其中主要方法是一个(或多个)事件方法。
●具体调停者(ConcreteMediator)角色:实现了抽象调停者所声明的事件方法。具体调停者知晓所有的具体同事类,并负责具体的协调各同事对象的交互关系。
●抽象同事类(Colleague)角色:定义出调停者到同事对象的接口。同事对象只知道调停者而不知道其余的同事对象。
●具体同事类(ConcreteColleague)角色:所有的具体同事类均从抽象同事类继承而来。实现自己的业务,在需要与其他同事通信的时候,就与持有的调停者通信,调停者会负责与其他的同事交互。

JS实现代码:

CD光驱

function CDDriver( mediator ) {
  //持有一个调停者对象
  this.mediator = mediator;
  /**
   * 获取当前同事类对应的调停者对象
   */
  this.getMediator = function() {
    return mediator;
  }
 //光驱读取出来的数据
 this.data = "";
  /**
   * 获取光盘读取出来的数据
   */
  this.getData = function() {
    return this.data;
  }
  /**
   * 读取光盘
   */
  this.readCD = function(){
    //逗号前是视频显示的数据,逗号后是声音
    this.data = "西游记,老孙来也!";
    //通知主板,自己的状态发生了改变
    this.getMediator().changed(this);
  }
}

CPU处理器

function CPU( mediator ) {
 //持有一个调停者对象
 this.mediator = mediator;
 /**
  * 获取当前同事类对应的调停者对象
  */
 this.getMediator = function() {
   return mediator;
 }
  //分解出来的视频数据
  this.videoData = "";
  //分解出来的声音数据
  this.soundData = "";
  /**
   * 获取分解出来的视频数据
   */
  this.getVideoData = function() {
    return this.videoData;
  }
  /**
   * 获取分解出来的声音数据
   */
  this.getSoundData = function() {
    return this.soundData;
  }
  /**
   * 处理数据,把数据分成音频和视频的数据
   */
  this.executeData = function(data){
    //把数据分解开,前面是视频数据,后面是音频数据
    var array = data.split(",");
    this.videoData = array[0];
    this.soundData = array[1];
    //通知主板,CPU完成工作
    this.getMediator().changed(this);
  }
}

显卡

function VideoCard( mediator ) {
  //持有一个调停者对象
  this.mediator = mediator;
  /**
   * 获取当前同事类对应的调停者对象
   */
  this.getMediator = function() {
    return mediator;
  }
  /**
   * 显示视频数据
   */
  this.showData = function(data){
    console.log("正在播放的是:" + data);
  }
}

声卡

function SoundCard( mediator ){
  //持有一个调停者对象
  this.mediator = mediator;
  /**
   * 获取当前同事类对应的调停者对象
   */
  this.getMediator = function() {
    return mediator;
  }
  /**
   * 按照声频数据发出声音
   */
  this.soundData = function(data){
    console.log("输出音频:" + data);
  }
}

具体调停者类

function MainBoard() {
  //需要知道要交互的同事类——光驱类
  this.cdDriver = null;
  //需要知道要交互的同事类——CPU类
  this.cpu = null;
  //需要知道要交互的同事类——显卡类
  this.videoCard = null;
  //需要知道要交互的同事类——声卡类
  this.soundCard = null;
  this.setCdDriver = function(cdDriver) {
    this.cdDriver = cdDriver;
  }
  this.setCpu = function(cpu) {
    this.cpu = cpu;
  }
  this.setVideoCard = function(videoCard) {
    this.videoCard = videoCard;
  }
  this.setSoundCard = function(soundCard) {
    this.soundCard = soundCard;
  }
  this.changed = function(c) {
    if(c instanceof CDDriver){
      //表示光驱读取数据了
      this.opeCDDriverReadData(c);
    }else if(c instanceof CPU){
      this.opeCPU(c);
    }
  }
  /**
   * 处理光驱读取数据以后与其他对象的交互
   */
  this.opeCDDriverReadData = function(cd){
    //先获取光驱读取的数据
    var data = cd.getData();
    //把这些数据传递给CPU进行处理
    cpu.executeData(data);
  }
  /**
   * 处理CPU处理完数据后与其他对象的交互
   */
  this.opeCPU = function(cpu){
    //先获取CPU处理后的数据
    var videoData = cpu.getVideoData();
    var soundData = cpu.getSoundData();
    //把这些数据传递给显卡和声卡展示出来
    this.videoCard.showData(videoData);
    this.soundCard.soundData(soundData);
  }
}

客户端

//创建调停者——主板
var mediator = new MainBoard();
//创建同事类
var cd = new CDDriver(mediator);
var cpu = new CPU(mediator);
var vc = new VideoCard(mediator);
var sc = new SoundCard(mediator);
//让调停者知道所有同事
mediator.setCdDriver(cd);
mediator.setCpu(cpu);
mediator.setVideoCard(vc);
mediator.setSoundCard(sc);
//开始看电影,把光盘放入光驱,光驱开始读盘
 cd.readCD();

打印效果

调停者模式的优点

● 松散耦合:调停者模式通过把多个同事对象之间的交互封装到调停者对象里面,从而使得同事对象之间松散耦合,基本上可以做到互补依赖。这样一来,同事对象就可以独立地变化和复用,而不再像以前那样“牵一处而动全身”了。
● 集中控制交互:多个同事对象的交互,被封装在调停者对象里面集中管理,使得这些交互行为发生变化的时候,只需要修改调停者对象就可以了,当然如果是已经做好的系统,那么就扩展调停者对象,而各个同事类不需要做修改。
● 多对多变成一对多:没有使用调停者模式的时候,同事对象之间的关系通常是多对多的,引入调停者对象以后,调停者对象和同事对象的关系通常变成双向的一对多,这会让对象的关系更容易理解和实现。

调停者模式的缺点

调停者模式的一个潜在缺点是,过度集中化。如果同事对象的交互非常多,而且比较复杂,当这些复杂性全部集中到调停者的时候,会导致调停者对象变得十分复杂,而且难于管理和维护。

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

为什么Node.js会成为Web应用开发?

在Node.js中如何获取文件上传进度?

在javascript中如何实现最长公共子序列

The above is the detailed content of JavaScript Mediator Pattern (Detailed Tutorial). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software