Files
design-patterns/02-structural/proxy/LazyConnectionProxy.java

53 lines
1.7 KiB
Java

package proxy;
/**
* Virtual Proxy — delays creating the RealDatabaseConnection until
* the first actual query is made. If no query is ever made (e.g.,
* the service is initialized but never used in this request),
* the expensive connection is never opened.
*
* This is exactly how Hibernate proxies work: entities are not
* loaded from the database until you access a field on them.
*/
public class LazyConnectionProxy implements DatabaseConnection {
private final String url;
private RealDatabaseConnection real; // null until first use
public LazyConnectionProxy(String url) {
this.url = url;
System.out.println("[Proxy] Created for " + url + " (real connection NOT opened yet)");
}
// Lazy initialization — create and connect only on first real need
private void initIfNeeded() {
if (real == null) {
System.out.println("[Proxy] First access — initializing real connection...");
real = new RealDatabaseConnection(url);
real.connect();
}
}
@Override
public void connect() {
// Proxy absorbs the connect() call — real connection opened lazily
System.out.println("[Proxy] connect() called — deferring to first query");
}
@Override
public String executeQuery(String sql) {
initIfNeeded(); // NOW we actually need the connection
return real.executeQuery(sql);
}
@Override
public void disconnect() {
if (real != null) {
real.disconnect();
real = null;
} else {
System.out.println("[Proxy] disconnect() called but connection was never opened");
}
}
}