Add all 23 GoF design pattern implementations (2026-06-13)

This commit is contained in:
Ankur
2026-06-13 21:44:56 +05:30
commit a5beb61425
106 changed files with 2977 additions and 0 deletions

View File

@@ -0,0 +1,52 @@
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");
}
}
}