Proxy
Provide a placeholder that controls access to another object.
Use it when
You need lazy loading, access control, caching or logging around an object.
/**
* Proxy: a caching stand-in for a slow exchange-rate API.
*
* Real-world scenario: a shop converts prices to the customer's currency. The
* rate API is slow and charges per call, but rates barely change within minutes.
* A proxy with the same interface sits in front of the real service: it calls
* the API the first time and answers from its cache after that. Code using the
* service can't tell the difference.
*
* Note: this is the design pattern. JavaScript's built-in Proxy object is a
* lower-level language feature for intercepting property access.
*/
const RATES: Record<string, number> = { EUR: 0.92, GBP: 0.79, INR: 83.1 }; // stands in for the web
// Subject: the interface shared by the real service and the proxy.
interface RateService {
/** How many units of `currency` one US dollar buys. */
getRate(currency: string): number;
}
// Real subject: does the expensive work.
class ExchangeRateAPI implements RateService {
calls = 0;
getRate(currency: string): number {
this.calls += 1;
console.log(` (calling the rate API for ${currency}...)`);
return RATES[currency];
}
}
// Proxy: same interface, controls access to the real subject.
class CachedRateService implements RateService {
private readonly api: ExchangeRateAPI;
private readonly cache = new Map<string, number>();
constructor(api: ExchangeRateAPI) {
this.api = api;
}
getRate(currency: string): number {
let rate = this.cache.get(currency);
if (rate === undefined) {
rate = this.api.getRate(currency);
this.cache.set(currency, rate);
}
return rate;
}
}
function showPrice(rates: RateService, usd: number, currency: string): void {
// Client code: works with any RateService, real or proxy.
const converted = usd * rates.getRate(currency);
console.log(`$${usd.toFixed(2)} = ${converted.toFixed(2)} ${currency}`);
}
function clientCode(): void {
const api = new ExchangeRateAPI();
const rates = new CachedRateService(api);
const orders: Array<[number, string]> = [
[49.99, "EUR"],
[15.0, "EUR"],
[120.0, "GBP"],
[8.5, "EUR"],
];
for (const [usd, currency] of orders) {
showPrice(rates, usd, currency);
}
console.log(`Prices shown: ${orders.length}, real API calls: ${api.calls}`);
}
clientCode();
// Output:
// (calling the rate API for EUR...)
// $49.99 = 45.99 EUR
// $15.00 = 13.80 EUR
// (calling the rate API for GBP...)
// $120.00 = 94.80 GBP
// $8.50 = 7.82 EUR
// Prices shown: 4, real API calls: 2How it works
| Role | Classes | What it does |
|---|---|---|
| Subject | RateService | The getRate() interface shared by the real service and the proxy |
| Real subject | ExchangeRateAPI | The slow, paid API that does the real work |
| Proxy | CachedRateService | Same interface; calls the API once per currency, then answers from a Map cache |
| Client | showPrice() | Works with any RateService and can't tell it's talking to a proxy |