Посередник (шаблон проєктування): відмінності між версіями

[неперевірена версія][перевірена версія]
Вилучено вміст Додано вміст
Немає опису редагування
Доданий приклад мовою Typescript
Рядок 671:
tc.tearDown()
 
</syntaxhighlight>
}}
 
=== TypeScript ===
{{Hider_hiding
| title = Приклад реалізації мовою [[TypeScript]]
| content =
<syntaxhighlight lang="TypeScript">
@Injectable()
class EventMediator
{
private customerChangedSubject$ = new BehaviorSubject<CustomerData>(null);
public customerChanged = this.customerChangedSubject$.asObservable();
 
public notifyOnCustomerChanged(customerData: CustomerData): void {
this.customerChangedSubject$.next(customerData);
}
 
private productChangedSubject$ = new BehaviorSubject<ProductData>(null);
public productChanged = this.productChangedSubject$.asObservable();
 
public notifyOnProductChanged(productData: ProductData): void {
this.productChangedSubject$.next(productData);
}
}
 
// надсилання подій
this.eventMediator.notifyOnCustomerChanged(new CustomerData());
 
// обробка подій
this.eventMediator.customerChanged.subscribe(c => this.customer = c);
</syntaxhighlight>
}}
 
{{Hider_hiding
| title = Приклад реалізації мовою [[TypeScript]] (Рішення на основі інтеграційної шини подій)
| content =
<syntaxhighlight lang="TypeScript">
enum Events {
CustomerSelected
}
 
class EmitEvent{
constructor(public name: Events, value?: any) { }
}
 
@Injectable()
class EventBus
{
private subject = new Subject<any>();
 
on(event: Events, action: any): Subscription {
return this.subject
.pipe(
filter((e: EmitEvent) => e.name === event),
map((e: EmitEvent) => e.value),
).subscribe(action);
}
 
emit(event: EmitEvent): void {
this.subject.next(event);
}
 
}
 
// надсилання подій
this.eventBus.emit(new EmitEvent(Events.CustomerSelected), new CustomerData());
 
// обробка подій
this.eventBus.on(Events.CustomerSelected, c => this.customer = c);
</syntaxhighlight>
}}