The decorator pattern allows adding new functionality to an individual object dynamically at runtime without affecting other instances of the same class. It involves wrapping the original class with concrete decorator classes that contain the additional responsibilities. In the example, a window object is decorated with scroll bar functionality by nesting decorator classes like VerticalScrollBarDecorator and HorizontalScrollBarDecorator that extend an abstract WindowDecorator class and wrap the decorated window object. This allows constructing windows with any combination of scroll bars without subclassing the window for each possibility.
7. FOR EXAMPLE
Given a GUI window object, we want to add any of the
following features to the window:
Horizontal scroll bar
Vertical scroll bar
Border
How can one display a window object such that it is able
to display any combination of these features without
writing a class for each individual combination?
9. DECORATOR PATTERN
Extends (decorates) the functionality of a certain object
at run-time
Decorating takes place independently of other instances
of the same class
The decorator class wraps around the original class or
object that is to be decorated
13. CODE—THE WINDOW
// the Window interface
interface Window {
public void draw(); // draws the Window
}
// implementation of a simple Window without any scrollbars
class SimpleWindow implements Window {
public void draw() {
// draw simple window
}
}
14. CODE—THE DECORATOR
// abstract decorator class - note that it implements Window
abstract class WindowDecorator implements Window {
protected Window decoratedWindow; // the Window being decorated
public WindowDecorator (Window decoratedWindow) {
this.decoratedWindow = decoratedWindow;
}
public void draw() {
decoratedWindow.draw();
}
}
15. CODE—THE DECORATOR
// the first concrete decorator which adds vertical scrollbar functionality
class VerticalScrollBarDecorator extends WindowDecorator {
public VerticalScrollBarDecorator (Window decoratedWindow) {
super(decoratedWindow);
}
public void draw() {
decoratedWindow.draw();
drawVerticalScrollBar();
}
private void drawVerticalScrollBar() {
// draw the vertical scrollbar
}
}
16. CODE—THE DECORATOR
// the second concrete decorator which adds horizontal scrollbar
functionality
class HorizontalScrollBarDecorator extends WindowDecorator {
public HorizontalScrollBarDecorator (Window decoratedWindow) {
super(decoratedWindow);
}
public void draw() {
decoratedWindow.draw();
drawHorizontalScrollBar();
}
private void drawHorizontalScrollBar() {
// draw the horizontal scrollbar
}
}
17. CODE—THE MAIN
public class DecoratedWindowTest {
public static void main(String[] args) {
// create a decorated Window with horizontal and vertical scrollbars
Window decoratedWindow = new HorizontalScrollBarDecorator (
new VerticalScrollBarDecorator(new SimpleWindow()));
}
}