Difference between the Composite Pattern and Decorator Pattern?

coder picture coder · Feb 10, 2010 · Viewed 31.9k times · Source

What is the difference between the Composite Pattern and Decorator Pattern?

Answer

Pavan picture Pavan · Jan 5, 2012

The structure of composite pattern and decorator look the same but they have different intent.

Composite gives an unified interface to a leaf and composite.

Decorator decorator gives additional feature to leaf, while giving unified interface.


Examples

Composite pattern: classic windows folders and files. Windows folders are composites. files are leaves. A double click on either of them opens the file/folder - double click is unified interface.

Decorator pattern: Buffered io - java.io.FileWriter and java.io.BufferedWriter both extend java.io.Writer. java.io.BufferedWriter is composite and FileWriter is leaf. BufferedWriter adds additional responsibility (or feature) of buffering to FileWriter. write() method is unified interface, whereas buffering is additional feature.