Decorator Pattern

Structural

What is it?

Dynamically adds behaviors or responsibilities to objects without modifying their structure.

Why use it?

The Decorator pattern adds new functionality to an existing object without altering its structure. This is useful for extending the behavior of classes in a flexible and reusable way. For instance, you can add logging, data validation, or formatting to objects dynamically without modifying the core class.

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
// Decorator Pattern Example

// Base coffee class
class Coffee {
  constructor() {
    this.description = 'Simple coffee';
    this.cost = 2;
  }
  
  getDescription() {
    return this.description;
  }
  
  getCost() {
    return this.cost;
  }
}

// Base decorator class
class CoffeeDecorator extends Coffee {
  constructor(coffee) {
    super();
    this.coffee = coffee;
  }
  
  getDescription() {
    return this.coffee.getDescription();
  }
  
  getCost() {
    return this.coffee.getCost();
  }
}

// Concrete decorators
class MilkDecorator extends CoffeeDecorator {
  constructor(coffee) {
    super(coffee);
  }
  
  getDescription() {
    return this.coffee.getDescription() + ', milk';
  }
  
  getCost() {
    return this.coffee.getCost() + 0.5;
  }
}

class SugarDecorator extends CoffeeDecorator {
  constructor(coffee) {
    super(coffee);
  }
  
  getDescription() {
    return this.coffee.getDescription() + ', sugar';
  }
  
  getCost() {
    return this.coffee.getCost() + 0.2;
  }
}

class WhipCreamDecorator extends CoffeeDecorator {
  constructor(coffee) {
    super(coffee);
  }
  
  getDescription() {
    return this.coffee.getDescription() + ', whip cream';
  }
  
  getCost() {
    return this.coffee.getCost() + 0.7;
  }
}

class CaramelDecorator extends CoffeeDecorator {
  constructor(coffee) {
    super(coffee);
  }
  
  getDescription() {
    return this.coffee.getDescription() + ', caramel';
  }
  
  getCost() {
    return this.coffee.getCost() + 0.8;
  }
}

// Usage
let coffee = new Coffee();
console.log(`${coffee.getDescription()} - $${coffee.getCost()}`);

// Add milk
coffee = new MilkDecorator(coffee);
console.log(`${coffee.getDescription()} - $${coffee.getCost()}`);

// Add sugar
coffee = new SugarDecorator(coffee);
console.log(`${coffee.getDescription()} - $${coffee.getCost()}`);

// Add whip cream
coffee = new WhipCreamDecorator(coffee);
console.log(`${coffee.getDescription()} - $${coffee.getCost()}`);

// Create a complex coffee order
let complexCoffee = new Coffee();
complexCoffee = new MilkDecorator(complexCoffee);
complexCoffee = new MilkDecorator(complexCoffee); // Double milk
complexCoffee = new CaramelDecorator(complexCoffee);
complexCoffee = new WhipCreamDecorator(complexCoffee);
console.log(`\nComplex order: ${complexCoffee.getDescription()} - $${complexCoffee.getCost()}`);

// Another example: Text formatting decorators
class Text {
  constructor(content) {
    this.content = content;
  }
  
  render() {
    return this.content;
  }
}

class TextDecorator extends Text {
  constructor(text) {
    super();
    this.text = text;
  }
  
  render() {
    return this.text.render();
  }
}

class BoldDecorator extends TextDecorator {
  render() {
    return `<b>${this.text.render()}</b>`;
  }
}

class ItalicDecorator extends TextDecorator {
  render() {
    return `<i>${this.text.render()}</i>`;
  }
}

class UnderlineDecorator extends TextDecorator {
  render() {
    return `<u>${this.text.render()}</u>`;
  }
}

// Usage
let text = new Text('Hello World');
text = new BoldDecorator(text);
text = new ItalicDecorator(text);
text = new UnderlineDecorator(text);
console.log(text.render()); // <u><i><b>Hello World</b></i></u>

// Function decorator example(more JavaScript-like)
function withLogging(fn) {
  return function(...args) {
    console.log(`Calling function ${fn.name} with arguments:`, args);
    const result = fn.apply(this, args);
    console.log(`Function ${fn.name} returned:`, result);
    return result;
  };
}

function withTiming(fn) {
  return function(...args) {
    const start = performance.now();
    const result = fn.apply(this, args);
    const end = performance.now();
    console.log(`Function ${fn.name} took ${end - start}ms`);
    return result;
  };
}

// Original function
function calculateSum(a, b) {
  return a + b;
}

// Decorate the function
const decoratedSum = withTiming(withLogging(calculateSum));
decoratedSum(5, 3);

Quick Facts

Category
Structural
Common Use Cases
Object composition, interface adaptation

Other Structural Patterns