Proxy & Decorator Patterns0%

Proxy & Decorator Patterns

Beginner12 min read•Updated: Jul 11, 2026
Study Materials

Proxy & Decorator Patterns in Modern JavaScript

Structural design patterns manage how objects and classes are composed into larger architectures. The Proxy Pattern and the Decorator Pattern add functionality to existing objects without modifying their underlying source code.


1. The Proxy Pattern

A Proxy acts as an intermediary or surrogate for another object, intercepting operations (property access, assignment, function invocation) to add access control, caching, or logging.

JavaScript provides native language-level support via the Proxy object:

JavaScript
const user = {
id: 101,
username: 'alex_dev',
role: 'editor',
salary: 85000
};
 
// Security Proxy: Protects sensitive salary property
const secureUserProxy = new Proxy(user, {
get(target, prop, receiver) {
if (prop === 'salary') {
throw new Error('Access Denied: You do not have clearance to view salary.');
}
return Reflect.get(target, prop, receiver);
},
 
set(target, prop, value, receiver) {
if (prop === 'role' && value === 'admin') {
throw new Error('Unauthorized: Cannot grant admin privileges directly.');
}
return Reflect.set(target, prop, value, receiver);
}
});
 
console.log(secureUserProxy.username); // "alex_dev"
// secureUserProxy.salary; // Error: Access Denied!
// secureUserProxy.role = 'admin'; // Error: Unauthorized!

2. Virtual Proxy for Lazy Loading

A Virtual Proxy delays the instantiation of an expensive resource until it is actually accessed:

JavaScript
class Heavy3DModel {
constructor(modelPath) {
console.log(`[Expensive] Loading 3D model meshes from: ${modelPath}`);
this.modelPath = modelPath;
}
render() { console.log(`Rendering 3D model ${this.modelPath}`); }
}
 
class Lazy3DModelProxy {
constructor(modelPath) {
this.modelPath = modelPath;
this.realModel = null; // Instantiation deferred!
}
 
render() {
if (!this.realModel) {
this.realModel = new Heavy3DModel(this.modelPath);
}
this.realModel.render();
}
}
 
const proxyModel = new Lazy3DModelProxy('/assets/car.obj');
// No heavy loading has occurred yet!
console.log('App loaded.');
 
// Loading happens ONLY when render() is called:
proxyModel.render();

3. The Decorator Pattern

The Decorator Pattern dynamically attaches additional responsibilities and behaviors to an object without altering its class definition.

JavaScript
// Base Component
class Coffee {
cost() { return 5; }
description() { return 'Simple Coffee'; }
}
 
// Decorator 1: Milk
function withMilk(coffee) {
const originalCost = coffee.cost();
const originalDesc = coffee.description();
return {
...coffee,
cost: () => originalCost + 1.5,
description: () => `${originalDesc}, with Steamed Milk`
};
}
 
// Decorator 2: Caramel
function withCaramel(coffee) {
const originalCost = coffee.cost();
const originalDesc = coffee.description();
return {
...coffee,
cost: () => originalCost + 2.0,
description: () => `${originalDesc}, with Caramel Drizzle`
};
}
 
// Stacking decorators dynamically:
let myOrder = new Coffee();
myOrder = withMilk(myOrder);
myOrder = withCaramel(myOrder);
 
console.log(myOrder.description()); // "Simple Coffee, with Steamed Milk, with Caramel Drizzle"
console.log(`Total: $${myOrder.cost()}`); // Total: $8.5

4. Comparing Proxy vs. Decorator

FeatureProxy PatternDecorator Pattern
IntentControls, intercepts, and manages access to an objectDynamically adds new features and responsibilities
InterfaceTypically mirrors target interface identicallyEnhances or expands target interface
RelationshipOften instantiated internally or created as wrapperComposed and chained by the client

Interactive Quiz

Practice Quiz

Question 1
What is the primary purpose of the Proxy Pattern?
Question 2
What native JavaScript object allows intercepting fundamental operations like property lookup and assignment?
Question 3
What is a "Virtual Proxy"?
Question 4
How does the Decorator Pattern differ from standard Class Inheritance?
Question 5
What standard JavaScript API should be used inside Proxy traps to perform default behavior on the target?
Next Lesson

TypedArrays & ArrayBuffers

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

PrevNext