Skip to main content

What is the essence of the Decorator pattern?

Decorator is a structural pattern that lets you dynamically add new behavior to an object without changing its class and without breaking the open/closed principle (OCP).


1. The Core Idea

Instead of creating many subclasses to extend functionality, a decorator wraps an object in another object that implements the same interface, but adds extra behavior before or after calling the original methods.


2. When to Use It

  • When you need to extend an object's behavior at runtime, rather than at inheritance time.
  • When it is impossible or undesirable to change the source code of the class (for example, it comes from a third-party library).
  • When you need to combine several features without causing an explosion of subclasses.

3. Example (Java)

java
interface DataSource { void write(String data); } class FileDataSource implements DataSource { public void write(String data) { System.out.println("Writing to file: " + data); } } class EncryptionDecorator implements DataSource { private DataSource wrappee; public EncryptionDecorator(DataSource source) { this.wrappee = source; } public void write(String data) { data = encrypt(data); wrappee.write(data); } private String encrypt(String data) { return "Encrypted(" + data + ")"; } }

Usage:

java
DataSource source = new EncryptionDecorator(new FileDataSource()); source.write("Hello");

Result: FileDataSource works as before, but now the data is encrypted before being written.


4. Advantages

  • Behavior can be added dynamically, without changing the source class.
  • You can combine several decorators (logging + compression + encryption).
  • Supports the principle of composition over inheritance.

5. Summary

Decorator is a way to "put extra features on" an object, while leaving its interface unchanged. It turns rigid inheritance into a flexible, dynamic extension of behavior.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.