一、Mediator是什么?
Mediator是一种设计模式,旨在通过降低对象之间的直接通信来促进松散耦合并支持可重用性。它可以让你更轻松地维护应用程序的代码,因为它可以将代码分解成许多较小、更容易管理的部分。对于需要共享信息的组件,这个模式特别适用。
在JavaScript应用程序中,Mediator模式是指一个在多个对象之间协调交互的对象(中介者)。
在Mediator模式中,客户端组件将请求发送到中介者对象,然后中介者对象决定如何将请求路由到一个或多个处理程序组件。
二、Mediator的优点
Mediator模式具有以下几个优点:
1. 降低耦合
Mediator模式可以降低对象的耦合性,因为它把对象之间的交互集中在了一个对象中,相互之间没有直接的通信和依赖关系。这样,当一个组件发生变化时,对其他组件的影响将得到降低。
2. 代码重用
Mediator模式可以将交互性代码分离,使得你可以将它们放入可复用的部件中。这使得代码更易于维护和重用。
3. 简化系统维护
使用Mediator模式可以简化系统的维护。由于每个组件只需要与中介者交互,而不需要知道其他组件,因此修改系统将变得更容易和可管理。
4. 容易测试
Mediator模式会把相互依赖的组件解耦,并将其通过中介者协调,从而使得代码更容易测试。
三、Negotiator是什么?
Negotiator是另一种设计模式,它也是常用于解耦对象之间的交互。它允许对象相互交互,但该交互是松散的,因为有一个独立于其他对象的类来协调这种交互。
Negotiator模式的基本工作方式是将所有请求发送到协调员对象,然后协调员对象将请求路由到相应的命令处理程序对象。
四、Mediator和Negotiator的区别
Mediator和Negotiator模式都是为了解耦对象间的交互,但两种模式之间有几个不同点。Mediator模式将交互逻辑集中在中介者对象中,而Negotiator模式将其协调逻辑放在协调员对象中。此外,如果你需要更精细和具体的控制,则Negotiator模式通常可以更好地满足需求。
五、Meditor的实现
1. Mediator模式示例代码
“`
// Mediator
var Mediator = function() {
this.components = [];
};
Mediator.prototype.register = function(component) {
this.components.push(component);
component.setMediator(this);
};
Mediator.prototype.notify = function(sender, event) {
this.components.forEach(function(component) {
if (sender != component) {
component.receive(event);
}
});
};
// Component
var Component = function(name) {
this.name = name;
this.mediator = null;
};
Component.prototype.setMediator = function(mediator) {
this.mediator = mediator;
};
Component.prototype.send = function(event) {
console.log(this.name + ” sends event: ” + event);
this.mediator.notify(this, event);
};
Component.prototype.receive = function(event) {
console.log(this.name + ” receives event: ” + event);
};
“`
2. Negotiator模式示例代码
“`
// Command
var Command = function(receiver) {
this.receiver = receiver;
};
Command.prototype.execute = function() {
console.log(this.name + ” executes command”);
this.receiver.action();
};
// Receiver
var Receiver = function() {};
Receiver.prototype.action = function() {
console.log(“receiver actions”);
};
// Coordinator
var Coordinator = function() {
this.commands = [];
};
Coordinator.prototype.addCommand = function(command) {
this.commands.push(command);
};
Coordinator.prototype.executeCommands = function() {
this.commands.forEach(function(command) {
command.execute();
});
};
“`
原创文章,作者:TNCLZ,如若转载,请注明出处:https://www.506064.com/n/332036.html