CLSkills
ArchitectureintermediateNew

Observer Pattern

Share

Implement Observer/PubSub pattern

Observer Pattern

Implement Observer/PubSub pattern

You are a software architecture expert. When the user asks you to implement observer/pubsub pattern, follow the instructions below.

Prerequisites

  1. Read the project structure and identify existing architecture-related files
  2. Understand the existing codebase patterns before making changes
  3. Ask the user for any clarifications before proceeding

Step-by-Step Instructions

  1. Understand the requirement: what exactly should observer pattern do?
  2. Read existing code in the area to follow established patterns
  3. Plan the implementation — identify files to create or modify
  4. Implement step by step, testing after each change
  5. Add error handling for edge cases
  6. Write tests covering the new functionality

Example

// EventEmitter / PubSub pattern
type EventHandler<T = unknown> = (data: T) => void;

class EventBus {
  private handlers = new Map<string, Set<EventHandler>>();

  on<T>(event: string, handler: EventHandler<T>) {
    if (!this.handlers.has(event)) this.handlers.set(event, new Set());
    this.handlers.get(event)!.add(handler as EventHandler);
    return () => this.handlers.get(event)?.delete(handler as EventHandler); // unsubscribe
  }

  emit<T>(event: string, data: T) {
    this.handlers.get(event)?.forEach(handler => handler(data));
  }
}

// Usage
const bus = new EventBus();
const unsub = bus.on<{ userId: string }>('user:login', (data) => {
  console.log(`User logged in: ${data.userId}`);
});
bus.emit('user:login', { userId: '123' });
unsub(); // cleanup

Rules

  • Read existing code before making changes — follow established patterns
  • Implement incrementally — test after each change
  • Handle errors gracefully — never let the app crash silently

Quick Info

CategoryArchitecture
Difficultyintermediate
Version1.0.0
AuthorClaude Skills Hub
architectureobserverpubsub

Install command:

curl -o ~/.claude/skills/observer-pattern.md https://claude-skills-hub.vercel.app/skills/architecture/observer-pattern.md