90 likes | 240 Views
The Decorator Pattern Decorators in Java I/O classes. Decorator Pattern context. You want to attach additional functionality to an (existing) class dynamically… …without having to resort to sub-classing the existing class We don’t want a class explosion
E N D
The Decorator PatternDecorators in Java I/O classes SE-2811 Dr. Mark L. Hornick
Decorator Pattern context • You want to attach additional functionality to an (existing) class dynamically… • …without having to resort to sub-classing the existing class • We don’t want a class explosion • We want to allow classes to be easily “extended” to incorporate new behavior without modifying existing code.
+ doMoreStuff() SE-2811 Dr. Mark L. Hornick
How are decorators useful? • Decorators have the same super-type as the objects they decorate. • Why is this useful? • One or more decorators can be used to wrap an object. • Why is this useful?
The java.io package contains dozens of classes OutputStream, FileOutputStream, PipedOutputStream, DataOutputStream, ObjectOutputStream, PrintStream, PrintWriter, … Understanding the associations between them just by reading the Javadoc API is difficult SE-2811 Dr. Mark L. Hornick
Knowing that the input stream classes are based on the Decorator pattern can make things easier <<deprecated>> SE-2811 Dr. Mark L. Hornick
The Decorator pattern applied to output streams Only for error propagation in my Java version SE-2811 Dr. Mark L. Hornick
You can create custom stream decorators by extending FilterOutputStream and FilterInputStream • Exercise SE-2811 Dr. Mark L. Hornick
Comparison of Decorator with Strategy SE-2811 Dr. Mark L. Hornick