وفي نظم البرامجيات المعقدة، ولا سيما تلك التي تنطوي على أحداث ومكونات عديدة، يمكن أن تصبح إدارة المعالين أمراً صعباً.() وتتيح Mediator Pattern ] حلاً فعالاً عن طريق إضفاء المركزية على الاتصالات والحد من أوجه الاعتماد المباشرة بين المكونات.

ما هو الوسيط باترن؟

إن الوسيط باترن هو نمط تصميم سلوكي يحدد غرضا (الوسيط) يلخص كيف تتفاعل مجموعة من الأشياء، وبدلا من أن ترسل هذه الأشياء مباشرة رسائل إلى الوسيط الذي ينسق التفاعلات، ويساعد هذا النهج في فك الارتباط بين العناصر وتبسيط مسارات الاتصالات المعقدة.

فوائد استخدام الوسيط باترن

  • Reduces dependencies: componentss no longer need to know about each other directly.
  • Improves maintainability:] Changes in one component require fewer modifications elsewhere.
  • Enhances scalability:] New components can be added with minimal impact on existing code.
  • Centralizes control:] Communication logical is managed in one place, streamlineing debugging and updates.

تنفيذ نظام " دورية الوسطاء " في نظم الأحداث

ولتنفيذ خطة الوسطاء، اتبع هذه الخطوات:

  • Define the Mediator interface:] Establish methods for communication between components.
  • Create concrete mediator:] Implement the interface to manage interactions.
  • Modify components:] Ensure components communicate via the mediator rather than directly.
  • Handle events centrally:] The mediator processes events and coordinates responses.

ففي إحدى معاهد التفتيش المشتركة المعقدة مثلاً، يمكن أن ترسل مختلف النوافذ إلى الوسيط أحداثاً تستكمل فيها نماذج أخرى أو تحفز على اتخاذ إجراءات، وتمنع هذه المجموعة من أن تكون للأنواع علاقة مباشرة ببعضها البعض، مما يجعل النظام أكثر مرونة وسهولة.

مسلسل " مقاطع "

وفيما يلي مثال مبسط في جافاسكريب:

class Mediator {
 constructor() {
 this.components = {};
 }
 register(componentName, component) {
 this.components[componentName] = component;
 component.setMediator(this);
 }
 notify(sender, event) {
 if (sender === 'Button') {
 this.components['TextBox'].update('Button clicked!');
 }
 }
}

class Button {
 setMediator(mediator) {
 this.mediator = mediator;
 }
 click() {
 this.mediator.notify('Button', 'click');
 }
}

class TextBox {
 update(message) {
 console.log('TextBox updated:', message);
 }
}

const mediator = new Mediator();
const button = new Button();
const textBox = new TextBox();

mediator.register('Button', button);
mediator.register('TextBox', textBox);

button.click(); // Output: TextBox updated: Button clicked!

خاتمة

ويساعد تنفيذ نظام " دورية الوسطاء " في نظم الأحداث المعقدة على الحد من المعالين وتحسين نظام الوحدات وجعل النظام أسهل للحفاظ عليه، ومن خلال إضفاء الطابع المركزي على الاتصالات، يمكن للمطورين أن يخلقوا تطبيقات أكثر مرونة وقابلية للاتساع يسهل توسيعها وإلغاءها.