Decorator (Structural)
Intent / problem it solves
Attach additional responsibilities to an object dynamically and transparently. Alternative to subclass explosion for cross-cutting features (logging, caching, compression).
When to use / when NOT
Use when behavior stacks orthogonally (IO wrappers, HTTP middleware, streams).
Avoid when a small interface plus explicit composition functions is clearer, or when order-dependent stacks become confusing—consider Chain of Responsibility or pipelines.
Structure
Decorator implements the same interface as the component, delegates to a wrapped instance, and adds behavior before/after.
Go example
package main
import (
"fmt"
"strings"
)
type Writer interface {
Write(text string) string
}
type BaseWriter struct{}
func (BaseWriter) Write(text string) string { return text }
type UpperWriter struct{ inner Writer }
func (wrapper UpperWriter) Write(text string) string {
return strings.ToUpper(wrapper.inner.Write(text))
}
type PrefixWriter struct {
inner Writer
prefix string
}
func (wrapper PrefixWriter) Write(text string) string {
return wrapper.prefix + wrapper.inner.Write(text)
}
func main() {
var pipeline Writer = PrefixWriter{
inner: UpperWriter{inner: BaseWriter{}},
prefix: "MSG:",
}
fmt.Println(pipeline.Write("hello"))
}JavaScript example
class DataSource {
read() {
throw new Error('override');
}
}
class MemorySource extends DataSource {
constructor(payload) {
super();
this.payload = payload;
}
read() {
return this.payload;
}
}
class LoggingDecorator extends DataSource {
constructor(inner, label) {
super();
this.inner = inner;
this.label = label;
}
read() {
const value = this.inner.read();
console.log(this.label, 'read', value);
return value;
}
}
const source = new LoggingDecorator(new MemorySource('alpha'), 'cache');
console.log(source.read());Interview phrase
“Decorator stacks behaviors like onion layers while preserving the original type’s interface—think io decorators in Go or Express middleware.”
Related LLD case studies
Link from LLD for middleware, stream transforms, or pricing adjustments in LLD case studies.
Last updated on
Spotted something unclear or wrong on this page?