Imagine fetching a heavy user profile from a database. You use a Proxy to delay that expensive database call until the exact moment you actually need the data (Lazy Loading).
public interface UserRepository {
String getUserData();
}
- The real, heavy database call
public class RealUserRepository implements UserRepository {
public RealUserRepository() {
System.out.println("Connecting to DB... (Heavy operation)");
}
public String getUserData() { return "User Data from DB"; }
}
- The PROXY (Controls access)
public class UserRepositoryProxy implements UserRepository {
private RealUserRepository realRepository;
public String getUserData() {
// Intercepting the call! Only initialize if we absolutely have to.**
if (realRepository == null) {
realRepository = new RealUserRepository();
}
return realRepository.getUserData();
}
}