# Proxy

> Control access to an object by wrapping it in a Proxy — add lazy loading, caching, logging, access control, or remote invocation transparently.

- **Category**: Software Design
- **Subcategory**: structural
- **Canonical URL**: https://designpattern.fyi/patterns/proxy/

---

## Description
**Intent**: Provide a placeholder that intercepts access to the real object so you can add behavior before or after without the client knowing.

**Context**: You need to load a heavy object only when it's first accessed (lazy init), add access control before operations, cache results of expensive calls, or forward calls to a remote object. Modifying the real object or the client to add this behavior would violate separation of concerns.

**Solution**: Create a Proxy that implements the same interface as the real object. Client code talks to the Proxy, not knowing the difference. The Proxy performs its cross-cutting concern (lazy init, auth check, caching, logging) and then delegates to the real object.


## Use Cases
Use for lazy initialization of expensive objects, access control, caching expensive operations, logging/auditing, or wrapping remote services.



## Implementation Example

```javascript
class RealImage {
  constructor(filename) {
    this.filename = filename;
    this.loadFromDisk();
  }
  loadFromDisk() { console.log(`Loading ${this.filename}`); }
  display() { console.log(`Displaying ${this.filename}`); }
}

class ProxyImage {
  constructor(filename) { this.filename = filename; }
  display() {
    if (!this.realImage) {
      this.realImage = new RealImage(this.filename);
    }
    this.realImage.display();
  }
}

```



## Trade-offs


### Advantages

- Cross-cutting concerns (auth, caching, logging) added without touching the real object or clients.

- Lifecycle of the real object can be managed transparently by the Proxy.




### Considerations & Drawbacks

- Extra class and indirection for each proxied service.

- Proxy adds latency — every call goes through an extra layer.







---
**Reference**: [Original Source](https://refactoring.guru/design-patterns/proxy)

