JavaScript Design Patterns Sample twenty - intermediary model

Intermediary model (Mediator Pattern)

Definition: to reduce the complexity of communications among a plurality of objects and classes. 
Objective: The object that encapsulates an intermediary set of objects interact, intermediary keeping objects explicitly referring to each other, so that it loosely coupled, and can be changed independently of the interaction between them.
Scene: a controller model M is C and V of FIG identify MVC framework broker.
let mediator = (() => {
    let msg = {}
    return {
        register: (type, action) => {
            if (!msg[type]) msg[type] = []
            msg[type].push(action)
        },
        send: (type) => {
            if (msg[type]) {
                for (let i = 0; i < msg[type].length; i++) {
                    msg[type][i] && msg[type][i]()
                }
            }
        }
    }
})()

mediator.register('demo', () => {
    console.log('first')
})
mediator.register('demo', () => {
    console.log('second')
})
mediator.send('demo')

Git Address: https://github.com/skillnull/Design-Mode-Example

Guess you like

Origin www.cnblogs.com/Man-Dream-Necessary/p/12628537.html
Recommended