What is the difference between the Composite Pattern and Decorator Pattern?
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.
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.