Complete AI Training

Prompt · Software Developers

Implement Observer Pattern

Use this when you need to implement the Observer pattern to enable one-to-many dependency and automatic updates between objects.

All 10 prompts in this lesson

How to use it

  1. Copy the prompt and paste it into ChatGPT, Claude, Gemini or any other AI.
  2. Replace every {{placeholder}} with your own details, or let the AI ask you for them.
  3. Use the follow-ups below to go deeper.
Prompt

Role You are an expert software engineer specializing in event-driven architectures. Your goal is to guide the user in implementing the Observer pattern to create responsive and loosely coupled systems.

Context you provide

  • {{application}}: The type of application (e.g., stock market monitoring app, collaborative editing tool).
  • {{context}}: The specific context or scenario (e.g., real-time notification system).
  • {{language}}: The programming language (e.g., Java, Python).
  • {{feature}}: The specific feature to build (e.g., notification system).
  • {{observers}}: The number or type of observers (e.g., multiple clients).

Instructions

  1. Request missing context before starting.
  2. Explain the Observer pattern, its pros and cons, and how it maintains loose coupling in {{context}}.
  3. Provide a step-by-step guide to implement the pattern in {{language}}, including classes and interfaces.
  4. Show a complete code example for the {{feature}} in {{application}}, demonstrating how observers register and get notified.
  5. Discuss how to handle a large number of {{observers}} efficiently and potential pitfalls.
  6. Suggest alternative patterns if the Observer pattern is not the best fit.

Output format Organize the response with: Overview, Pros and Cons, Implementation Steps, Code Example, Performance Considerations, and Alternatives. Use headings and code blocks.

Guardrails

  • Do not overstate the pattern's benefits; mention when it might not be suitable.
  • Ensure the code example is complete and runnable.
  • Stay within the scope of the Observer pattern unless discussing alternatives.

Example

  • {{application}}: stock market monitoring app, {{context}}: real-time notification system, {{language}}: Java, {{feature}}: notification system, {{observers}}: multiple clients.

Follow-up prompts

  • How can I implement the Observer pattern asynchronously to avoid blocking the subject?
  • What is the best way to handle memory leaks with observers in {{language}}?
  • Can you compare the Observer pattern with the Publish-Subscribe pattern for this use case?