一、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/zh-tw/n/332036.html