using System.Collections.Generic;
PrinterService ps = new();
var pss = new PaperSupplierService(ps);
var tss = new TonerSupplierService(ps);
var cs = new CleanerService(ps);
interface IObserver<TNotification>
void Notify(TNotification notification);
class Observable<T, TNotification>
where T : IObserver<TNotification>
List<T> _observers = new ();
public void Add(T observer)
=> _observers.Add(observer);
public void Remove(T observer)
=> _observers.Remove(observer);
public void NotifyAll(TNotification notification)
foreach (var observer in _observers)
observer.Notify(notification);
class PrinterServiceNotification
public string DocumentId {get; private set;}
public PrinterServiceNotification(string documentId)
=> DocumentId = documentId;
public readonly Observable<IPrinterServiceObserver, PrinterServiceNotification>
public readonly Observable<IPrinterServiceObserver, PrinterServiceNotification>
public void Print(string documentId)
BeforePrinting.NotifyAll(new PrinterServiceNotification(documentId));
Console.WriteLine($"Printing {documentId}...");
AfterPrinting.NotifyAll(new PrinterServiceNotification(documentId));
interface IPrinterServiceObserver
: IObserver<PrinterServiceNotification>
class PaperSupplierService
: IPrinterServiceObserver
public PaperSupplierService(PrinterService ps)
=> ps.BeforePrinting.Add(this);
public void Notify(PrinterServiceNotification notification)
Console.WriteLine($"PSS: {notification.DocumentId}");
class TonerSupplierService
: IPrinterServiceObserver
public TonerSupplierService(PrinterService ps)
=> ps.BeforePrinting.Add(this);
public void Notify(PrinterServiceNotification notification)
=> Console.WriteLine($"TSS: {notification.DocumentId}");
: IPrinterServiceObserver
public CleanerService(PrinterService ps)
=> ps.AfterPrinting.Add(this);
public void Notify(PrinterServiceNotification notification)
=> Console.WriteLine($"CS: {notification.DocumentId}");