DecoratorVSProxy
The Problem
Scenario A — Decorator territory:
You have a NotificationService that sends push notifications. You want to add retry logic, then rate limiting, then logging — each as a separate, stackable layer. Each layer implements the same interface and wraps the next.
Scenario B — Proxy territory:
You have an ImageService that loads high-resolution images from S3. Loading is expensive. You want a stand-in that returns a placeholder until the real image is requested, then lazily loads it. The client should not know it's talking to a stand-in.
Why They Look Alike
Both wrap an object behind the same interface. Both delegate to the wrapped object. The class structure is identical: WrapperClass implements Interface, holds a reference to Interface, and forwards calls. This is the most confusing pair in GoF.
The Fundamental Difference
Decorator adds new behaviour to an existing object. Proxy controls access to an object.
Decorator: "I'll do what you do, PLUS something extra" (logging, metrics, retry, rate limiting). Proxy: "I'll decide IF and WHEN you get access" (lazy loading, caching, auth, remote access).
Decision Rule
| Clue | Pattern |
|---|---|
| "Add logging, metrics, retry, or transformation" | Decorator |
| "Control when or whether the real object is accessed" | Proxy |
| "Stack multiple independent wrappers" | Decorator |
| "Replace the object with a stand-in" | Proxy |
| "The real object always exists and is always called" | Decorator |
| "The real object might not exist yet or might not be called" | Proxy |
| "Enhances the result" | Decorator |
| "Guards the access" | Proxy |
Side-by-Side Code
Decorator — stacking extra behaviour
| 1 | interface NotificationService { |
| 2 | send(userId: string, message: string): Promise<boolean>; |
| 3 | } |
| 4 | |
| 5 | class PushNotificationService implements NotificationService { |
| 6 | async send(userId: string, message: string) { |
| 7 | console.log(`Push to ${userId}: ${message}`); |
| 8 | return true; |
| 9 | } |
| 10 | } |
| 11 | |
| 12 | // Decorator 1: retry on failure |
| 13 | class RetryDecorator implements NotificationService { |
| 14 | constructor(private inner: NotificationService, private maxRetries = 3) {} |
| 15 | |
| 16 | async send(userId: string, message: string) { |
| 17 | for (let i = 0; i < this.maxRetries; i++) { |
| 18 | const result = await this.inner.send(userId, message); |
| 19 | if (result) return true; |
| 20 | console.log(`Retry ${i + 1}/${this.maxRetries}`); |
| 21 | } |
| 22 | return false; |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | // Decorator 2: logging |
| 27 | class LoggingDecorator implements NotificationService { |
| 28 | constructor(private inner: NotificationService) {} |
| 29 | |
| 30 | async send(userId: string, message: string) { |
| 31 | console.log(`[LOG] Sending notification to ${userId}`); |
| 32 | const result = await this.inner.send(userId, message); |
| 33 | console.log(`[LOG] Result: ${result}`); |
| 34 | return result; |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | // Stack them |
| 39 | const service: NotificationService = new LoggingDecorator( |
| 40 | new RetryDecorator( |
| 41 | new PushNotificationService() |
| 42 | ) |
| 43 | ); |
| 44 | service.send("user_1", "Hello!"); // logged → retried → sent |
Proxy — controlling access
| 1 | interface ImageService { |
| 2 | getImage(id: string): Promise<Buffer>; |
| 3 | } |
| 4 | |
| 5 | class S3ImageService implements ImageService { |
| 6 | async getImage(id: string) { |
| 7 | console.log(`Expensive S3 download: ${id}`); |
| 8 | return Buffer.from(`image-data-${id}`); |
| 9 | } |
| 10 | } |
| 11 | |
| 12 | // Proxy: lazy loading — doesn't create the real service until needed |
| 13 | class LazyImageProxy implements ImageService { |
| 14 | private realService: S3ImageService | null = null; |
| 15 | |
| 16 | private getReal(): S3ImageService { |
| 17 | if (!this.realService) { |
| 18 | console.log("Initializing S3 connection (expensive)..."); |
| 19 | this.realService = new S3ImageService(); |
| 20 | } |
| 21 | return this.realService; |
| 22 | } |
| 23 | |
| 24 | async getImage(id: string) { |
| 25 | return this.getReal().getImage(id); |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | // Proxy: access control — checks permission before allowing access |
| 30 | class AuthImageProxy implements ImageService { |
| 31 | constructor( |
| 32 | private inner: ImageService, |
| 33 | private userRole: string, |
| 34 | ) {} |
| 35 | |
| 36 | async getImage(id: string) { |
| 37 | if (this.userRole !== "admin" && id.startsWith("private_")) { |
| 38 | throw new Error("Access denied: private images require admin role"); |
| 39 | } |
| 40 | return this.inner.getImage(id); |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | // Proxy: caching — avoids calling the real service if cached |
| 45 | class CachingImageProxy implements ImageService { |
| 46 | private cache = new Map<string, Buffer>(); |
| 47 | |
| 48 | constructor(private inner: ImageService) {} |
| 49 | |
| 50 | async getImage(id: string) { |
| 51 | if (this.cache.has(id)) { |
| 52 | console.log(`Cache hit: ${id}`); |
| 53 | return this.cache.get(id)!; |
| 54 | } |
| 55 | const data = await this.inner.getImage(id); |
| 56 | this.cache.set(id, data); |
| 57 | return data; |
| 58 | } |
| 59 | } |
Key difference: Every Decorator call always reaches the real object (with extras). A Proxy may short-circuit and never call the real object (cache hit, access denied, lazy not-yet-created).
The Grey Area
Caching can be argued either way. If the focus is "avoid the expensive call when possible" → Proxy (controlling access). If the focus is "enhance performance as an add-on layer" → Decorator. In interviews, acknowledge the overlap and explain your reasoning.
Scenario Quiz
?Knowledge Check
1You wrap a database repository to add query timing metrics. Every query still executes; you just measure it. Which pattern?
2You create a virtual proxy for a heavy Report object. The proxy holds the report ID but only loads the full report data when a method is actually called. Which pattern?
3NestJS Guards check if the user has the required role before the controller method runs. If not, the request is rejected. Which pattern?
4Express middleware that compresses response bodies. Every response gets compressed. Which pattern?
5A remote proxy makes network calls to a service on another machine, making it look like a local object. Which pattern?
6You wrap an API client to add request/response logging and automatic retry. Both always run; the real call is always made. Which pattern?
7The quick test: can the wrapper prevent the real object from being called?
8TypeORM's lazy relations return a Promise that loads the related entity only when awaited. Which pattern?