110 likes | 249 Views
Week 6, Class 1 & 2: Decorators. Return Exam Questions about lab due tomorrow in class? Threads Locking on null object invokeLater & the squares example Decorator & Java IO continued Decorator vs. List of Add-ons. Decorator Pattern context.
E N D
Week 6, Class 1 & 2:Decorators • Return Exam • Questions about lab due tomorrow in class? • Threads • Locking on null object • invokeLater & the squares example • Decorator & Java IO continued • Decorator vs. List of Add-ons SE-2811 Slide design: Dr. Mark L. Hornick Content: Dr. Hornick Errors: Dr. Yoder
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() + doMoreStuff() SE-2811 Dr. Mark L. Hornick
How are decorators useful? • Decorators have the same super-type as the objects they decorate. • Helps organize: e.g., can put all beverage objects in the same data-structure • Used when initializing super-class • One or more decorators can be used to wrap an object. • Why is this useful? • Can still get to specific & useful method • When creating the object • By casting back to cream (leaves open question: Is it cream?) • Test using instanceof • Can get more & more specific about the object with multiple decos. • Don’t need all the classes for all combinations
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
Decorator vs. Array of Add-ons SE-2811 Dr. Mark L. Hornick
Design Principles • T? Reduce coupling • Abstract classes are unliked • T Increase cohesion • T Encapsulate what varies • E.g. mocha class only cares about chocolate • Favor composition over inheritance • T Program to interfaces, not implementations • T Classes should be open for extension but closed for modification Which of these are met? SE-2811 Dr. Mark L. Hornick
Downsides • What are the disadvantages of decorators? • Need to pay attention to abstract classes & type SE-2811 Dr. Mark L. Hornick
SE-2811 Dr. Mark L. Hornick