Add all 23 GoF design pattern implementations (2026-06-13)
This commit is contained in:
51
02-structural/proxy/Main.java
Normal file
51
02-structural/proxy/Main.java
Normal file
@@ -0,0 +1,51 @@
|
||||
package proxy;
|
||||
|
||||
/**
|
||||
* Proxy Design Pattern — Runnable Demo
|
||||
*
|
||||
* Shows two proxy types:
|
||||
* 1. Virtual Proxy (lazy connection)
|
||||
* 2. Logging Proxy (cross-cutting concern)
|
||||
* 3. Proxy chaining (both together)
|
||||
*
|
||||
* Run: javac proxy/*.java && java proxy.Main
|
||||
* Article: https://ankurm.com/proxy-design-pattern-java/
|
||||
*/
|
||||
public class Main {
|
||||
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
System.out.println("=== Proxy Design Pattern Demo ===\n");
|
||||
|
||||
// --- Virtual Proxy: lazy connection ---
|
||||
System.out.println("-- Virtual Proxy (lazy loading) --");
|
||||
DatabaseConnection lazy = new LazyConnectionProxy("jdbc:postgresql://localhost/mydb");
|
||||
lazy.connect(); // absorbed by proxy, no real connection yet
|
||||
System.out.println("(no real connection yet — saved startup time)");
|
||||
System.out.println("Result: " + lazy.executeQuery("SELECT * FROM users WHERE id=1"));
|
||||
System.out.println("Result: " + lazy.executeQuery("SELECT COUNT(*) FROM orders"));
|
||||
lazy.disconnect();
|
||||
|
||||
System.out.println();
|
||||
|
||||
// --- Logging Proxy: wraps the real connection ---
|
||||
System.out.println("-- Logging Proxy --");
|
||||
DatabaseConnection real = new RealDatabaseConnection("jdbc:mysql://localhost/shopdb");
|
||||
real.connect();
|
||||
DatabaseConnection logged = new LoggingProxy(real);
|
||||
logged.executeQuery("SELECT * FROM products LIMIT 10");
|
||||
logged.disconnect();
|
||||
|
||||
System.out.println();
|
||||
|
||||
// --- Proxy chaining: lazy + logging ---
|
||||
System.out.println("-- Chained Proxies: Lazy + Logging --");
|
||||
DatabaseConnection chain =
|
||||
new LoggingProxy(
|
||||
new LazyConnectionProxy("jdbc:oracle://localhost/warehouse"));
|
||||
chain.connect();
|
||||
chain.executeQuery("SELECT SUM(quantity) FROM inventory");
|
||||
chain.disconnect();
|
||||
|
||||
System.out.println("\n=== Demo complete ===");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user