QA
Beginner LevelSoftware Engineering Principles

What is the Decorator Pattern and how does it dynamically add behavior to objects?

❓ Interview Prompt: Explain the Decorator Structural Pattern, wrapping target objects, extending behavior dynamically, and alternative to inheritance.

The Decorator Pattern allows behavior to be added to an individual object dynamically without affecting the behavior of other objects from the same class:

How It Works:

The Decorator class implements the same interface as the target object and wraps a reference to it, intercepting method calls to execute additional cross-cutting behavior (e.g. logging, encryption, caching).

Code Implementation Example

typescript
interface Coffee { getCost(): number; }
class SimpleCoffee implements Coffee { getCost() { return 5; } }

// Decorator wrapping Coffee instance
class MilkDecorator implements Coffee {
  constructor(private coffee: Coffee) {}
  getCost() { return this.coffee.getCost() + 2; } // Wraps & extends behavior!
}

const myCoffee = new MilkDecorator(new SimpleCoffee()); // Cost: 7
💡Wrapping objects dynamically with the Decorator pattern.
🎯 Interview Key Takeaway

Use the Decorator pattern to wrap objects dynamically with extra responsibilities without resorting to subclass inheritance.

#Decorator#Design Patterns#Structural#Beginner
Back to all Software Engineering Principles Questions→

More Software Engineering Principles Interview Questions

Beginner LevelSoftware Engineering Principles

Explain the 5 SOLID Principles of Object-Oriented Software Design with practical refactoring examples.

Beginner LevelSoftware Engineering Principles

What are DRY (Don't Repeat Yourself), KISS (Keep It Simple, Stupid), and YAGNI (You Aren't Gonna Need It)?

Beginner LevelSoftware Engineering Principles

Why is Composition Over Inheritance a fundamental object-oriented design principle?