- Forward


The Decorator Pattern
An Introduction with Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Motivation
Back SMYC Forward
  • Adding Capabilities to a Class:
    • Specialization
  • Adding Capabilities to an Object:
    • Needs to be done "dynamically" (i.e., at run time)
Examples of Use
Back SMYC Forward
  • I/O Streams in Java
  • Borders, etc.. on GUI components
A Model of the Decorator Pattern
Back SMYC Forward
decorator_pattern
An Example
Back SMYC Forward
decorator_pattern_printer-example
An Example (cont.)
Back SMYC Forward
javaexamples/decorator/Printer.java
 
An Example (cont.)
Back SMYC Forward
javaexamples/decorator/ConsolePrinter.java
 
An Example (cont.)
Back SMYC Forward
javaexamples/decorator/PrinterDecorator.java
 
An Example (cont.)
Back SMYC Forward
javaexamples/decorator/UppercasePrinter.java
 
An Example (cont.)
Back SMYC Forward
javaexamples/decorator/WrappingPrinter.java
 
An Example (cont.)
Back SMYC Forward
javaexamples/decorator/Driver.java
 
An Alternative Implementation
Back SMYC Forward
  • The Issue:
    • You need to decorate a class that does not implement an explicit interface
  • The Resolution:
    • Specialize the class to be decorated but still use delegation
An Alternative Implementation (cont.)
Back SMYC Forward

An Example

decorator_pattern_graphics-example
There's Always More to Learn
Back -