Add all 23 GoF design pattern implementations (2026-06-13)
This commit is contained in:
38
02-structural/adapter/Main.java
Normal file
38
02-structural/adapter/Main.java
Normal file
@@ -0,0 +1,38 @@
|
||||
package adapter;
|
||||
|
||||
/**
|
||||
* Adapter Design Pattern — Runnable Demo
|
||||
*
|
||||
* Demonstrates wrapping an incompatible StripeClient behind
|
||||
* the PaymentGateway interface your application expects.
|
||||
*
|
||||
* Run: javac adapter/*.java && java adapter.Main
|
||||
* Article: https://ankurm.com/adapter-design-pattern-java/
|
||||
*/
|
||||
public class Main {
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println("=== Adapter Design Pattern Demo ===\n");
|
||||
|
||||
// --- Object Adapter: Stripe ---
|
||||
System.out.println("-- Using Stripe via Adapter --");
|
||||
StripeClient stripeClient = new StripeClient("sk_test_4eC39HqLyjWDarjtT1zdp7dc");
|
||||
PaymentGateway stripeGateway = new StripePaymentAdapter(stripeClient);
|
||||
|
||||
OrderService orderService = new OrderService(stripeGateway);
|
||||
orderService.processOrder("ORD-001", "cus_abc123", 99.99);
|
||||
|
||||
System.out.println("\n-- Testing refund --");
|
||||
boolean refunded = stripeGateway.refund("ch_ORD-001", 99.99);
|
||||
System.out.println("Refund issued: " + refunded);
|
||||
|
||||
// --- JDK Example: InputStreamReader as Adapter ---
|
||||
System.out.println("\n-- JDK Adapter: InputStreamReader --");
|
||||
// InputStreamReader adapts InputStream (byte-based) to Reader (char-based)
|
||||
// The client (BufferedReader) only knows about Reader, not InputStream
|
||||
System.out.println("InputStreamReader wraps System.in (InputStream) as a Reader.");
|
||||
System.out.println("Your code reads chars; the adapter handles byte-to-char conversion.");
|
||||
|
||||
System.out.println("\n=== Demo complete ===");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user