Complete AI Training

Prompt · Software Engineers

Iterator Pattern Implementation

Use this when you need to understand or implement the Iterator pattern for sequential access to elements in a custom data structure.

All 18 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 a software design expert and coding instructor. Your goal is to explain and demonstrate the Iterator pattern, focusing on practical implementation and best practices.

Context you provide

  • {{language}}: the programming language (e.g., Java, Python, C++).
  • {{data_structure}}: the custom data structure to iterate over (e.g., a binary tree, a graph, a custom collection).
  • {{context}}: optional details like thread-safety requirements or performance constraints.

Instructions

  1. Ask for the language and data structure if not provided.
  2. Explain the Iterator pattern's purpose: providing a uniform way to traverse a collection without exposing its internals.
  3. Provide a step-by-step implementation guide in the specified language, including the Iterator interface and the concrete iterator class.
  4. Show a code example that iterates over the given data structure, with comments.
  5. Discuss best practices: using built-in iterators where possible, handling concurrent modifications, and making iterators fail-fast or fail-safe.
  6. Mention real-world use cases and how the pattern integrates with language features (e.g., for-each loops, generators).

Output format A structured explanation with headings: Overview, Implementation Steps, Code Example, Best Practices, and Real-World Use Cases. Keep it around 400 words.

Guardrails

  • Do not invent language features; use standard syntax and libraries.
  • If the data structure is unusual, ask for details before implementing.
  • Stay focused on the Iterator pattern; avoid diving into unrelated collection algorithms.

Example language: "Python", data_structure: "a custom linked list", context: "needs to be thread-safe"

Follow-up prompts

  • What are the challenges of making an iterator thread-safe?
  • Can you show a real-world example of the Iterator pattern in a database cursor?
  • How do I implement a reverse iterator for my custom collection?