Episode 9 — System Design / 9.4 — Structural Design Patterns
9.4 -- Exercise Questions: Structural Design Patterns
Practice questions for all five subtopics in Section 9.4. Mix of short-answer, code, diagrams, and scenario-based questions. Try each without looking back at the lesson files first.
How to use this material (instructions)
- Read lessons in order --
README.md, then9.4.athrough9.4.e. - Answer closed-book first -- only reopen a lesson after you have written something.
- Code questions -- write working JavaScript, then test in Node or a browser console.
- Redo misses -- retry wrong items the next day (spaced repetition).
- Interview prep -- pair with
9.4-Interview-Questions.mdfor polished wording.
9.4.a -- Adapter Pattern (Q1--Q8)
Q1. In one sentence, what problem does the Adapter pattern solve?
Q2. Draw an ASCII diagram showing the relationship between Client, Adapter, and Adaptee.
Q3. Explain the difference between an Object Adapter and a Class Adapter. Which is preferred in JavaScript and why?
Q4. You are integrating two logging libraries with different APIs:
- Library A:
logA.write(level, message) - Library B:
logB.output({ severity: level, text: message })
Write an Adapter that makes Library B conform to Library A's interface.
Q5. A legacy API returns user data as { fname: 'Jane', lname: 'Doe', electronic_mail: 'jane@old.com' }. Your app expects { firstName, lastName, email }. Write an adapter.
Q6. True/False (justify): "An Adapter adds new behavior to the adaptee."
Q7. Your checkout service currently uses Stripe directly. List the steps you would take to refactor it to use the Adapter pattern so it can also support PayPal.
Q8. How does the Adapter pattern support the Open/Closed Principle?
9.4.b -- Facade Pattern (Q9--Q16)
Q9. In one sentence, what is a Facade?
Q10. Draw an ASCII diagram showing a Facade sitting between a Client and three subsystems (TemplateEngine, SmtpClient, EmailQueue).
Q11. A developer argues: "A Facade is just a helper function." What is the key difference between a Facade and a helper/utility function?
Q12. You are building a video processing pipeline with these steps:
- Upload to storage
- Validate format
- Transcode to multiple resolutions
- Generate thumbnails
- Update database with URLs
- Send notification
Write the interface (method signatures) for a VideoProcessingFacade that hides all this from callers.
Q13. What is the difference between a Facade and an Adapter? Give a one-line distinction.
Q14. Explain the God Object anti-pattern and how a Facade can accidentally become one. What are three warning signs?
Q15. Scenario: Your frontend makes 5 separate API calls to render a dashboard (user, orders, recommendations, notifications, loyalty). How would an API Facade (API Gateway) improve this?
Q16. True/False (justify): "A Facade prevents clients from accessing subsystem classes directly."
9.4.c -- Proxy Pattern (Q17--Q26)
Q17. Name the four main types of proxies and give a one-sentence use case for each.
Q18. What is the critical interface requirement that distinguishes a Proxy from an Adapter?
Q19. Write a Virtual Proxy for an ExpensiveReport class. The real report takes 5 seconds to generate, but the proxy should defer generation until getReport() is called.
Q20. Write a Protection Proxy for a BankAccount class where only the account owner or an admin can call withdraw().
Q21. Write a Caching Proxy that wraps an API client. Cache responses for 30 seconds using a Map.
Q22. Explain how JavaScript's built-in Proxy class differs from the classical OOP Proxy pattern.
Q23. Using JavaScript's new Proxy(), create a proxy for an array that:
- Logs every access (get trap)
- Prevents setting negative indices (set trap)
Q24. Draw the flow of a request through three layered proxies: Logging -> Caching -> Protection -> Real Object.
Q25. True/False (justify): "A Proxy and a Decorator are the same thing because they both wrap an object with the same interface."
Q26. Give a real-world example where each proxy type is used:
- Virtual proxy in a web application
- Protection proxy in a REST API
- Caching proxy in a database layer
- Logging proxy in a microservice
9.4.d -- Decorator Pattern (Q27--Q36)
Q27. What problem does the Decorator pattern solve that inheritance cannot?
Q28. Explain why 3 optional behaviors would require 7 subclasses with inheritance but only 4 classes with Decorator.
Q29. Draw an ASCII diagram of three nested decorators wrapping a core object.
Q30. Write a withRetry(fn, maxRetries) higher-order function decorator that retries a failing async function up to maxRetries times.
Q31. Write a withTimeout(fn, ms) decorator that rejects if the wrapped function takes longer than ms milliseconds.
Q32. Given these decorators: withLogging, withCache, withRetry -- what is the behavioral difference between:
withLogging(withCache(withRetry(fn)))andwithCache(withLogging(withRetry(fn)))
Q33. How does Express middleware implement the Decorator pattern? Describe the flow of req through three middlewares.
Q34. Write a compose(...decorators) utility function that takes N decorator functions and returns a single decorator.
Q35. What is the difference between a Decorator and a Proxy? Give a scenario where you would use each.
Q36. Scenario: You have 5 cross-cutting concerns (logging, auth, caching, rate limiting, validation) applied to 10 API endpoints. Calculate:
- How many combinations with inheritance?
- How many classes/functions with decorators?
9.4.e -- Composite Pattern (Q37--Q44)
Q37. What are the three participants in the Composite pattern? Define each.
Q38. Draw a tree diagram for a file system with: root directory containing 2 subdirectories (src and tests), where src contains 2 files and tests contains 1 file.
Q39. Write the recursive getSize() method for a Directory class that contains both File (leaf) and Directory (composite) children.
Q40. Implement a shopping cart that supports both individual products and product bundles (which can contain other products or bundles). Each should respond to getPrice().
Q41. Why is it important that Leaf and Composite share the same interface in the Composite pattern?
Q42. Write a search(term) method that recursively searches a file system composite for files whose names contain term.
Q43. Scenario: You are building a permission system where permissions can be individual (canEditPosts) or groups (AdminPermissions = canEditPosts + canDeletePosts + canManageUsers). How would you model this with the Composite pattern?
Q44. Give three real-world examples of tree structures suitable for the Composite pattern (besides file systems).
Cross-Pattern Questions (Q45--Q50)
Q45. Complete this table:
| Pattern | Wraps how many objects? | Same interface? | Primary intent |
|---|---|---|---|
| Adapter | ? | ? | ? |
| Facade | ? | ? | ? |
| Proxy | ? | ? | ? |
| Decorator | ? | ? | ? |
| Composite | ? | ? | ? |
Q46. You need to:
- Integrate a third-party email service with a different API -> which pattern?
- Add caching to your database queries without modifying the query code -> which pattern?
- Build a nested comment system where comments can have replies (which can have replies...) -> which pattern?
- Simplify a complex checkout flow that coordinates payment, inventory, shipping, and notifications -> which pattern?
Q47. Draw an ASCII diagram showing how Adapter, Facade, Proxy, and Decorator all involve "wrapping" but for different reasons.
Q48. You are building an e-commerce product catalog where:
- Products can be individual items OR bundles
- Each product has a price (bundles aggregate children)
- You need to cache frequently-accessed products
- Product data comes from a third-party API with a different format
Which structural patterns would you combine and how?
Q49. Explain the phrase "favor composition over inheritance" and identify which structural patterns embody this principle.
Q50. For each pattern, name one well-known real-world implementation in the JavaScript/Node.js ecosystem:
- Adapter: ?
- Facade: ?
- Proxy: ?
- Decorator: ?
- Composite: ?
Answer Hints (short)
| Q | Hint |
|---|---|
| Q1 | Makes incompatible interfaces work together by translating one to the other. |
| Q6 | False -- Adapter only translates; Decorator adds behavior. |
| Q13 | Adapter translates one interface to another; Facade simplifies a complex subsystem. |
| Q16 | False -- Facade is a convenience layer; clients CAN still access subsystems directly. |
| Q18 | Proxy has the same interface as the real object; Adapter translates to a different interface. |
| Q25 | False -- same mechanism, different intent: Proxy controls access, Decorator adds behavior. |
| Q27 | Avoids combinatorial explosion of subclasses when combining optional behaviors. |
| Q36 | Inheritance: 2^5 - 1 = 31 subclasses; Decorators: 5 decorator functions + 1 base = 6 units. |
| Q41 | Uniform interface lets the client treat leaves and composites identically without type-checking. |
| Q46 | Adapter, Proxy (caching proxy), Composite, Facade (in order). |
<- Back to 9.4 -- Structural Design Patterns (README)