js实现中介者模式

中介者模式主要用于一个系统中存在大量的对象,而且这些大量的对象需要互相通信,因为两个对象需要通信,一个对象必须要持有另一个对象,这样就会导致,系统里,每个对象都互相引用,会引起混乱,中介者把所有的对象都统一管理起来,其他的对象通过中介者去和别的对象通信。

function A(mediator) {
    this.mediator = mediator;
}
A.prototype = {
    send: function(msg,receiver) {
        this.mediator.send(msg,'A',receiver);
    },
    receiveMsg: function(msg,sender) {
        console.log(sender+" say:"+msg)
    }
}

function B(mediator) {
    this.mediator = mediator;
}
B.prototype = {
    send: function(msg,receiver) {
        this.mediator.send(msg,'B',receiver);
    },
    receiveMsg: function(msg,sender) {
        console.log(sender+" say:"+msg)
    }
}
function Mediator() {
    this.A = new A(this);
    this.B = new B(this);
}
Mediator.prototype = {
    send: function(msg,sender,receiver) {
        try {
            this[receiver].receiveMsg(msg,sender);
        }
        catch(err) {
            console.log('receiver '+receiver+' is not exsit');
            this[sender].receiveMsg('receiver '+ receiver +' is not exsit','mediator');
        }
    }
}

var _mediator = new Mediator();
var _a = new A(_mediator);
var _b = new B(_mediator);
_a.send('hello i am A','B');
_b.send('hello i am B','A');

其中A,B可以抽象出一个公共的父类,这要看A,B有没有共同的地方,Mediator还可以根据对象间的通信的,类似于路由器或交换机一样,中介者需要知道通信者的发起者和接收者,就像路由器需要源ip和目的ip一样,不需要事先把方法写死,因为对象太多的时候,这种方法会导致中介者过于庞大,中介者应该抽象出对象间通信的各种功能,然后把接口对对象开放。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
装饰者模式是一种结构型设计模式,它允许将行为动态地添加到一个对象中,同时又不改变其原有的实现。装饰者模式通过创建一个包装对象,将原始对象进行包装,从而在运行时动态地添加新的功能。 在 JavaScript 中,装饰者模式可以通过对象扩展、类继承或者函数包装等方式来实现。下面以对象扩展为例进行说明: ```javascript // 定义一个基础组件类 class Component { operation() { return "基础功能"; } } // 定义一个装饰者类 class Decorator { constructor(component) { this.component = component; } operation() { return `${this.component.operation()},附加装饰功能`; } } // 使用示例 const component = new Component(); console.log(component.operation()); // 输出:基础功能 const decoratedComponent = new Decorator(component); console.log(decoratedComponent.operation()); // 输出:基础功能,附加装饰功能 ``` 在上面的示例中,`Component` 是基础组件类,`Decorator` 是装饰者类,它接收一个 `Component` 对象作为参数,并在其 `operation` 方法中调用原始对象的 `operation` 方法,并添加了额外的功能。 通过使用装饰者模式,我们可以动态地增加、组合和删除功能,而无需修改现有的代码。这种扩展性和灵活性使得装饰者模式在一些场景下非常有用,比如在不破坏原有类结构的情况下,对现有对象进行功能增强或行为修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值