← Back to scenarios
ScenarioCatalog DB

News publisher

Notify subscribers when a new article is published so applications and channels update automatically.

Problem

A publishing system must inform a changing set of subscriber applications and delivery channels about new articles without coupling the publisher to each concrete subscriber.

Related patterns

Implementations

Observer

TypeScriptApplication

Observer in TypeScript

Publishes deployment-status changes to independently subscribed notification channels.

TypeScript
interface DeploymentObserver {
  update(status: string): void;
}

class Deployment {
  private readonly observers = new Set<DeploymentObserver>();
  private status = "pending";

  subscribe(observer: DeploymentObserver) {
    this.observers.add(observer);
  }

  unsubscribe(observer: DeploymentObserver) {
    this.observers.delete(observer);
  }

  setStatus(status: string) {
    this.status = status;
    this.notify();
  }

  private notify() {
    for (const observer of this.observers) {
      observer.update(this.status);
    }
  }
}

class SlackNotifier implements DeploymentObserver {
  update(status: string) {
    console.log(`Slack: deployment is ${status}`);
  }
}

class DashboardNotifier implements DeploymentObserver {
  update(status: string) {
    console.log(`Dashboard updated: ${status}`);
  }
}

const deployment = new Deployment();

deployment.subscribe(new SlackNotifier());
deployment.subscribe(new DashboardNotifier());

deployment.setStatus("running");
deployment.setStatus("completed");

Associated technologies