|
| 1 | +# Proxy Design Pattern in TypeScript |
| 2 | + |
| 3 | +## π Overview |
| 4 | +The **Proxy Design Pattern** is a **structural pattern** that provides a substitute or placeholder for another object to control access, add security, cache results, or perform lazy initialization. |
| 5 | + |
| 6 | +In this example, we implement a **ProxyServer** that acts as a security layer for a **Bank** object. The proxy ensures that only authenticated users can perform transactions while allowing non-authenticated users to check account holder names. |
| 7 | + |
| 8 | +--- |
| 9 | + |
| 10 | +## π **Flow of Execution** |
| 11 | +1. **`Bank` Class**: Stores user account details and provides methods for withdrawal, balance checking, and retrieving account holder names. |
| 12 | +2. **`ProxyServer` Class**: Acts as a middle layer, enforcing authentication before allowing access to sensitive operations like withdrawals and balance checks. |
| 13 | +3. **Client Code**: |
| 14 | + - Tries to withdraw money via the proxy. |
| 15 | + - If authenticated, the proxy forwards the request to the real `Bank` object. |
| 16 | + - If not authenticated, the proxy blocks access and displays an error. |
| 17 | + |
| 18 | +--- |
| 19 | + |
| 20 | +## π **Code Implementation** |
| 21 | +```typescript |
| 22 | +// Define a common interface for both Bank and Proxy |
| 23 | +interface Account { |
| 24 | + withdraw(accountNumber: string, amount: number): void; |
| 25 | + checkBalance(accountNumber: string): number; |
| 26 | + nonAuthCheckPersonName(accountNumber: string): string; |
| 27 | +} |
| 28 | + |
| 29 | +// Real Bank implementation |
| 30 | +class Bank implements Account { |
| 31 | + private accounts: { [key: string]: { name: string; balance: number } } = {}; |
| 32 | + |
| 33 | + constructor(name: string, accountNumber: string, balance: number) { |
| 34 | + this.accounts[accountNumber] = { name, balance }; |
| 35 | + } |
| 36 | + |
| 37 | + withdraw(accountNumber: string, amount: number): void { |
| 38 | + const account = this.accounts[accountNumber]; |
| 39 | + if (!account) { |
| 40 | + console.log("Account not found."); |
| 41 | + return; |
| 42 | + } |
| 43 | + |
| 44 | + if (amount > account.balance) { |
| 45 | + console.log("Insufficient funds."); |
| 46 | + return; |
| 47 | + } |
| 48 | + |
| 49 | + account.balance -= amount; |
| 50 | + console.log(`Withdrawn: $${amount}. Remaining balance: $${account.balance}`); |
| 51 | + } |
| 52 | + |
| 53 | + checkBalance(accountNumber: string): number { |
| 54 | + return this.accounts[accountNumber]?.balance ?? 0; |
| 55 | + } |
| 56 | + |
| 57 | + nonAuthCheckPersonName(accountNumber: string): string { |
| 58 | + return this.accounts[accountNumber]?.name ?? "Unknown"; |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +// Proxy class implementing the same interface |
| 63 | +class ProxyServer implements BankAccount { |
| 64 | + private bank: Bank; |
| 65 | + private isAuthenticated: boolean; |
| 66 | + |
| 67 | + constructor(bank: Bank, isAuthenticated: boolean) { |
| 68 | + this.bank = bank; |
| 69 | + this.isAuthenticated = isAuthenticated; |
| 70 | + } |
| 71 | + |
| 72 | + withdraw(accountNumber: string, amount: number): void { |
| 73 | + if (!this.isAuthenticated) { |
| 74 | + console.log("Access Denied: Authentication required."); |
| 75 | + return; |
| 76 | + } |
| 77 | + this.bank.withdraw(accountNumber, amount); |
| 78 | + } |
| 79 | + |
| 80 | + checkBalance(accountNumber: string): number { |
| 81 | + if (!this.isAuthenticated) { |
| 82 | + console.log("Access Denied: Authentication required."); |
| 83 | + return 0; |
| 84 | + } |
| 85 | + return this.bank.checkBalance(accountNumber); |
| 86 | + } |
| 87 | + |
| 88 | + nonAuthCheckPersonName(accountNumber: string): string { |
| 89 | + return this.bank.nonAuthCheckPersonName(accountNumber); |
| 90 | + } |
| 91 | +} |
| 92 | + |
| 93 | +// Usage example |
| 94 | +const realBank = new Bank("Alice", "12345", 1000); |
| 95 | +const proxy = new ProxyBankAccount(realBank, false); |
| 96 | + |
| 97 | +proxy.withdraw("12345", 200); // Output: Access Denied: Authentication required. |
| 98 | + |
| 99 | +const authProxy = new ProxyBankAccount(realBank, true); |
| 100 | +authProxy.withdraw("12345", 200); // Withdraws successfully |
| 101 | +``` |
| 102 | + |
| 103 | +--- |
| 104 | + |
| 105 | +## π― **Benefits of the Proxy Pattern** |
| 106 | +β
**Access Control** β Restricts unauthorized users from performing sensitive actions. |
| 107 | +β
**Security Enhancement** β Prevents direct access to important objects. |
| 108 | +β
**Lazy Initialization** β Loads objects only when needed, optimizing resource usage. |
| 109 | +β
**Logging & Monitoring** β Allows tracking of actions before execution. |
| 110 | +β
**Performance Optimization** β Implements caching or request batching. |
| 111 | + |
| 112 | +--- |
| 113 | + |
| 114 | +## π **When to Use the Proxy Pattern?** |
| 115 | +πΉ **Security Proxies** β Control access to sensitive objects based on authentication. |
| 116 | +πΉ **Cache Proxy** β Store previously fetched data to improve performance. |
| 117 | +πΉ **Logging Proxy** β Log requests before executing operations. |
| 118 | +πΉ **Lazy Loading Proxy** β Load expensive objects only when required. |
| 119 | +πΉ **Virtual Proxy** β Represent resource-intensive objects with lightweight stand-ins. |
| 120 | + |
| 121 | +--- |
| 122 | + |
| 123 | +## π **Conclusion** |
| 124 | +The Proxy Design Pattern is an excellent way to enforce **security, access control, and optimization** without modifying the original class. By wrapping the **real object** with a **proxy**, we ensure that all interactions are controlled and managed efficiently. π |
| 125 | + |
0 commit comments