Proxy
Provide surrogate or placeholder for another object
Overview
The Proxy pattern is a structural design pattern that lets you provide a substitute or placeholder for another object. A proxy controls access to the original object, allowing you to perform something either before or after the request gets through to the original object.
Key Concepts
Subject Interface: Shared by both RealSubject and Proxy
RealSubject: The object being proxied
Proxy: Controls access to RealSubject
Types: Virtual (lazy init), Protection (auth), Remote (network), Cache (caching)
Code Example
1// Subject Interface
2public interface VideoFetcher {
3 String getVideo(String videoId);
4}
5
6// Real Subject
7public class YouTubeService implements VideoFetcher {
8 @Override
9 public String getVideo(String videoId) {
10 System.out.println("Connecting to YouTube...");
11 System.out.println("Downloading video " + videoId);
12 // Simulate network latency
13 return "Video Data for " + videoId;
14 }
15}
16
17// Proxy (Caching Proxy)
18import java.util.HashMap;
19import java.util.Map;
20
21public class CachedYouTubeProxy implements VideoFetcher {
22 private YouTubeService youtubeService;
23 private Map<String, String> cache = new HashMap<>();
24
25 public CachedYouTubeProxy() {
26 this.youtubeService = new YouTubeService();
27 }
28
29 @Override
30 public String getVideo(String videoId) {
31 if (!cache.containsKey(videoId)) {
32 System.out.println("Cache miss! Fetching from original service...");
33 cache.put(videoId, youtubeService.getVideo(videoId));
34 } else {
35 System.out.println("Cache hit! Returning cached data...");
36 }
37 return cache.get(videoId);
38 }
39}
40
41// Client
42public class Main {
43 public static void main(String[] args) {
44 VideoFetcher fetcher = new CachedYouTubeProxy();
45
46 // First fetch
47 System.out.println(fetcher.getVideo("cat_video_1"));
48
49 // Second fetch (cached)
50 System.out.println(fetcher.getVideo("cat_video_1"));
51 }
52}The CachedYouTubeProxy intercepts the getVideo request. If the video is not cached, it delegates to the real YouTubeService and then caches the result.
When to Use
Lazy initialization (Virtual proxy): when object creation is expensive
Access control (Protection proxy): for checking permissions
Local execution of a remote service (Remote proxy)
Logging requests (Logging proxy)
Caching query results (Caching proxy)
💡 Interview Tips
Always discuss the different types of proxies (Virtual, Protection, Cache)
A great practical example is Hibernate/JPA implementing lazy loading
Distinguish Proxy from Decorator: Proxy manages lifecycle/access, Decorator adds behavior