Proxy Pattern

Structural

What is it?

Provides a surrogate or placeholder for another object to control access to it.

Why use it?

The Proxy pattern provides a surrogate or placeholder for another object to control access to it. This can be useful for implementing lazy initialization, access control, logging, or even remote proxies.

Code Example

typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
// Proxy Pattern Example

// Virtual Proxy - Lazy Loading
class ExpensiveResource {
  constructor() {
    console.log('ExpensiveResource: Creating expensive resource(takes time)...');
    // Simulate expensive operation
    this.data = this._loadData();
  }
  
  _loadData() {
    // Simulate loading large data
    const data = [];
    for (let i = 0; i < 1000000; i++) {
      data.push(Math.random());
    }
    return data;
  }
  
  process() {
    console.log(`Processing ${this.data.length} items...`);
    return this.data.reduce((a, b) => a + b, 0);
  }
}

class LazyResourceProxy {
  constructor() {
    this.resource = null;
  }
  
  process() {
    if (!this.resource) {
      console.log('Proxy: Creating resource on first use...');
      this.resource = new ExpensiveResource();
    }
    return this.resource.process();
  }
}

// Usage
console.log('Creating proxy(instant)...');
const proxy = new LazyResourceProxy();
console.log('Proxy created!');

console.log('\nFirst call to process():');
proxy.process(); // Resource created here

console.log('\nSecond call to process():');
proxy.process(); // Resource already exists

// Protection Proxy - Access Control
class BankAccount {
  constructor(balance = 0) {
    this.balance = balance;
  }
  
  deposit(amount) {
    this.balance += amount;
    console.log(`Deposited: $${amount}. Balance: $${this.balance}`);
  }
  
  withdraw(amount) {
    if (amount <= this.balance) {
      this.balance -= amount;
      console.log(`Withdrawn: $${amount}. Balance: $${this.balance}`);
    } else {
      console.log('Insufficient funds!');
    }
  }
  
  getBalance() {
    return this.balance;
  }
}

class SecureBankAccountProxy {
  constructor(account, pin) {
    this.account = account;
    this.correctPin = pin;
    this.authenticated = false;
  }
  
  authenticate(pin) {
    this.authenticated = pin === this.correctPin;
    if (this.authenticated) {
      console.log('Authentication successful!');
    } else {
      console.log('Authentication failed!');
    }
    return this.authenticated;
  }
  
  deposit(amount) {
    if (this.authenticated) {
      return this.account.deposit(amount);
    }
    console.log('Please authenticate first!');
  }
  
  withdraw(amount) {
    if (this.authenticated) {
      return this.account.withdraw(amount);
    }
    console.log('Please authenticate first!');
  }
  
  getBalance() {
    if (this.authenticated) {
      return this.account.getBalance();
    }
    console.log('Please authenticate first!');
    return null;
  }
}

// Usage
const account = new BankAccount(1000);
const secureAccount = new SecureBankAccountProxy(account, '1234');

console.log('\nTrying to access without authentication:');
secureAccount.withdraw(100);

console.log('\nAuthenticating with wrong PIN:');
secureAccount.authenticate('0000');
secureAccount.withdraw(100);

console.log('\nAuthenticating with correct PIN:');
secureAccount.authenticate('1234');
secureAccount.withdraw(100);
secureAccount.deposit(500);

// Logging Proxy
class Calculator {
  add(a, b) { return a + b; }
  subtract(a, b) { return a - b; }
  multiply(a, b) { return a * b; }
  divide(a, b) { return a / b; }
}

class LoggingCalculatorProxy {
  constructor(calculator) {
    this.calculator = calculator;
    this.logs = [];
  }
  
  add(a, b) {
    const result = this.calculator.add(a, b);
    this._log('add', [a, b], result);
    return result;
  }
  
  subtract(a, b) {
    const result = this.calculator.subtract(a, b);
    this._log('subtract', [a, b], result);
    return result;
  }
  
  multiply(a, b) {
    const result = this.calculator.multiply(a, b);
    this._log('multiply', [a, b], result);
    return result;
  }
  
  divide(a, b) {
    const result = this.calculator.divide(a, b);
    this._log('divide', [a, b], result);
    return result;
  }
  
  _log(operation, args, result) {
    const logEntry = {
      timestamp: new Date(),
      operation,
      arguments: args,
      result
    };
    this.logs.push(logEntry);
    console.log(`[${logEntry.timestamp.toISOString()}] ${operation}(${args.join(', ')}) = ${result}`);
  }
  
  getLogs() {
    return this.logs;
  }
}

// Usage
const calc = new Calculator();
const loggedCalc = new LoggingCalculatorProxy(calc);

console.log('\nPerforming calculations with logging:');
loggedCalc.add(5, 3);
loggedCalc.multiply(4, 7);
loggedCalc.divide(20, 4);

// JavaScript Proxy API Example
const target = {
  name: 'John',
  age: 30,
  _private: 'secret'
};

const handler = {
  get(target, property) {
    if (property.startsWith('_')) {
      console.log(`Access denied to private property: ${property}`);
      return undefined;
    }
    console.log(`Accessing property: ${property}`);
    return target[property];
  },
  
  set(target, property, value) {
    if (property.startsWith('_')) {
      console.log(`Cannot set private property: ${property}`);
      return false;
    }
    console.log(`Setting property: ${property} = ${value}`);
    target[property] = value;
    return true;
  }
};

const proxiedObject = new Proxy(target, handler);

console.log('\nUsing JavaScript Proxy:');
console.log(proxiedObject.name); // Allowed
console.log(proxiedObject._private); // Blocked
proxiedObject.age = 31; // Allowed
proxiedObject._private = 'new secret'; // Blocked

Quick Facts

Category
Structural
Common Use Cases
Object composition, interface adaptation

Other Structural Patterns