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
Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

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.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)