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.
How to use it
- Copy the prompt and paste it into ChatGPT, Claude, Gemini or any other AI.
- Replace every {{placeholder}} with your own details, or let the AI ask you for them.
- 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
- Request missing context before starting.
- Explain the Observer pattern, its pros and cons, and how it maintains loose coupling in {{context}}.
- Provide a step-by-step guide to implement the pattern in {{language}}, including classes and interfaces.
- Show a complete code example for the {{feature}} in {{application}}, demonstrating how observers register and get notified.
- Discuss how to handle a large number of {{observers}} efficiently and potential pitfalls.
- 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?