Home Web Front-end JS Tutorial Mediator mode of javascript design pattern Mediator_javascript skills

Mediator mode of javascript design pattern Mediator_javascript skills

May 16, 2016 pm 04:23 PM
javascript intermediary pattern Design Patterns

1. Overall summary

1, the author briefly discusses

Let’s take a simple analogy from daily life. We go to a housing agency to rent a house. The housing agency forms an intermediary between the renter and the landlord. A renter doesn't care whose house he rents from. Nor does the landlord care who he rents to. Because of the existence of intermediaries, this transaction has become so convenient.

In the process of software development, you will inevitably encounter a situation where multiple classes or subsystems interact with each other, and the interaction is very cumbersome, resulting in each class having to know the classes it needs to interact with, so that their The coupling will appear to be extremely powerful. If one move affects the whole body, the consequences will be serious. The bear will be very angry! ~~~~(>_<)~~~~

Okay, now that the question has been raised, let’s invite our protagonist in this issue—the intermediary mode

The function of the mediator is to encapsulate the interaction between objects. If the operation of an object will cause changes to other related objects, and the object does not want to handle these relationships by itself, then you can find an intermediary and let it handle these troublesome relationships. Look at the small example below:

Copy code The code is as follows:

var Participant = function(name) {
    this.name = name;
    this.chatroom = null;
};
Participant.prototype = {
    send: function(message, to) {
        this.chatroom.send(message, this, to);
    },
    receive: function(message, from) {
        log.add(from.name " to " this.name ": " message);
    }
};
var Chatroom = function() {
    var participants = {};
    return {
        register: function(participant) {
            participants[participant.name] = participant;
            participant.chatroom = this;
        },
        send: function(message, from, to) {
            if (to) {                  
                to.receive(message, from);   
            } else {                    
                for (key in participants) {  
                    if (participants[key] !== from) {
                        participants[key].receive(message, from);
                    }
                }
            }
        }
    };
};
var log = (function() {
    var log = "";
    return {
        add: function(msg) { log = msg "n"; },
        show: function() { alert(log); log = ""; }
    }
})();
function run() {
    var yoko = new Participant("Yoko");
    var john = new Participant("John");
    var paul = new Participant("Paul");
    var ringo = new Participant("Ringo");
    var chatroom = new Chatroom();
    chatroom.register(yoko);
    chatroom.register(john);
    chatroom.register(paul);
    chatroom.register(ringo);
    yoko.send("All you need is love.");
    yoko.send("I love you John.");
    john.send("Hey, no need to broadcast", yoko);
    paul.send("Ha, I heard that!");
    ringo.send("Paul, what do you think?", paul);
    log.show();
}

在示例代码中我们有四个参与者,加入聊天会话通过注册一个聊天室(中介)。每个参与者的参与对象的代表。参与者相互发送消息和聊天室的处理路由。

这里的聊天室对象就起到了中介的作用,协调其他的对象,进行合理的组织,降低耦合。

二,源码案例参考

我们应该很熟悉MVC三层模型实体模型(Model)、视图表现层(View)还有控制层(Control/Mediator)。

控制层便是位于表现层与模型层之间的中介者。笼统地说MVC也算是中介者模式在框架设计中的一个应用。

三,案例引入

复制代码 代码如下:

function Player(name) {
    this.points = 0;
    this.name = name;
}
Player.prototype.play = function () {
    this.points = 1;
    mediator.played();
};
var scoreboard = {
    element:document.getElementById('results'),
    update:function (score) {
        var i, msg = '';
        for (i in score) {
            if (score.hasOwnProperty(i)) {
                msg = '

' i ': ';
                msg = score[i];
                msg = '

';
            }
        }
        this.element.innerHTML = msg;
    }
};
var mediator = {
    players:{},
    setup:function () {
        var players = this.players;
        players.home = new Player('Home');
        players.guest = new Player('Guest');
    },
    played:function () {
        var players = this.players,
                score = {
                    Home:players.home.points,
                    Guest:players.guest.points
                };
        scoreboard.update(score);
    },
    keypress:function (e) {
        e = e || window.event;
        if (e.which === 49) {
            mediator.players.home.play();
            return;
        }
        if (e.which === 48) {
            mediator.players.guest.play();
            return;
        }
    }
};
mediator.setup();
window.onkeypress = mediator.keypress;
setTimeout(function () {
    window.onkeypress = null;
    console.log('Game over!');
}, 30000);

四,总结一下

Why Mediator ?

各个对象之间的交互操作非常多,每个对象的行为操作都依赖彼此对方,修改一个对象的行为,同时会涉及到修改很多其他对象的行为,

如果使用Mediator模式,可以使各个对象间的耦合松散,只需关心和 Mediator的关系,使多对多的关系变成了一对多的关系,

可以降低系统的复杂性,提高可修改扩展性。

使用中介者模式的场合

1.一组定义良好的对象,现在要进行复杂的通信。

2.定制一个分布在多个类中的行为,而又不想生成太多的子类。

可以看出,中介对象主要是用来封装行为的,行为的参与者就是那些对象,但是通过中介者,这些对象不用相互知道。(迪米特法则的具体实现)

使用中介者模式的优点:

1.降低了系统对象之间的耦合性,使得对象易于独立的被复用。

2.提高系统的灵活性,使得系统易于扩展和维护。

使用中介者模式的缺点:

中介者模式的缺点是显而易见的,因为这个“中介“承担了较多的责任,所以一旦这个中介对象出现了问题,那么整个系统就会受到重大的影响。

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The difference between design patterns and architectural patterns in Java framework The difference between design patterns and architectural patterns in Java framework Jun 02, 2024 pm 12:59 PM

In the Java framework, the difference between design patterns and architectural patterns is that design patterns define abstract solutions to common problems in software design, focusing on the interaction between classes and objects, such as factory patterns. Architectural patterns define the relationship between system structures and modules, focusing on the organization and interaction of system components, such as layered architecture.

Analysis of the Decorator Pattern in Java Design Patterns Analysis of the Decorator Pattern in Java Design Patterns May 09, 2024 pm 03:12 PM

The decorator pattern is a structural design pattern that allows dynamic addition of object functionality without modifying the original class. It is implemented through the collaboration of abstract components, concrete components, abstract decorators and concrete decorators, and can flexibly expand class functions to meet changing needs. In this example, milk and mocha decorators are added to Espresso for a total price of $2.29, demonstrating the power of the decorator pattern in dynamically modifying the behavior of objects.

PHP design pattern practical case analysis PHP design pattern practical case analysis May 08, 2024 am 08:09 AM

1. Factory pattern: Separate object creation and business logic, and create objects of specified types through factory classes. 2. Observer pattern: allows subject objects to notify observer objects of their state changes, achieving loose coupling and observer pattern.

How design patterns deal with code maintenance challenges How design patterns deal with code maintenance challenges May 09, 2024 pm 12:45 PM

Design patterns solve code maintenance challenges by providing reusable and extensible solutions: Observer Pattern: Allows objects to subscribe to events and receive notifications when they occur. Factory Pattern: Provides a centralized way to create objects without relying on concrete classes. Singleton pattern: ensures that a class has only one instance, which is used to create globally accessible objects.

The wonderful use of the adapter pattern in Java design patterns The wonderful use of the adapter pattern in Java design patterns May 09, 2024 pm 12:54 PM

The Adapter pattern is a structural design pattern that allows incompatible objects to work together. It converts one interface into another so that the objects can interact smoothly. The object adapter implements the adapter pattern by creating an adapter object containing the adapted object and implementing the target interface. In a practical case, through the adapter mode, the client (such as MediaPlayer) can play advanced format media (such as VLC), although it itself only supports ordinary media formats (such as MP3).

PHP Design Patterns: Test Driven Development in Practice PHP Design Patterns: Test Driven Development in Practice Jun 03, 2024 pm 02:14 PM

TDD is used to write high-quality PHP code. The steps include: writing test cases, describing the expected functionality and making them fail. Write code so that only the test cases pass without excessive optimization or detailed design. After the test cases pass, optimize and refactor the code to improve readability, maintainability, and scalability.

Application of design patterns in Guice framework Application of design patterns in Guice framework Jun 02, 2024 pm 10:49 PM

The Guice framework applies a number of design patterns, including: Singleton pattern: ensuring that a class has only one instance through the @Singleton annotation. Factory method pattern: Create a factory method through the @Provides annotation and obtain the object instance during dependency injection. Strategy mode: Encapsulate the algorithm into different strategy classes and specify the specific strategy through the @Named annotation.

What are the advantages and disadvantages of using design patterns in java framework? What are the advantages and disadvantages of using design patterns in java framework? Jun 01, 2024 pm 02:13 PM

The advantages of using design patterns in Java frameworks include: enhanced code readability, maintainability, and scalability. Disadvantages include complexity, performance overhead, and steep learning curve due to overuse. Practical case: Proxy mode is used to lazy load objects. Use design patterns wisely to take advantage of their advantages and minimize their disadvantages.

See all articles