Decorator

Definition: The decorator pattern adds additional responsibilities to an object dynamically. Decorators are a flexible alternative to subclassing for extending functionality.

Usage: Use the decorator pattern when you need to modify the behavior of an object in certain cases, but don't need to modify every object of that class. In the example, it actually restricts behavior in a way.

Example

/* Widgets are gui objects like Swing JComponents.*/
interface Widget {
	reactToMouseEvent(MouseEvent event)
}

/* This class decorates another Widget so that it only receives mouse events within a certain area.*/
class BoundedWidget implements Widget {
	BoundedWidget(Widget widget, Rectangle bound) {
		this.widget = widget;
		this.bound = bound;
	}

	reactToMouseEvent(MouseEvent event) {
		if(event is within bound)
			widget.reactToMouseEvent(event)
	}

	Widget widget;
	Rectangle bound;
}

This sort of class is used in Lucky's Puzzle Carnival to create buttons that only receive mouse events within a portion of the area where they are drawn. This is useful because the animation that shows the button being clicked is wider than the image for when it's not being clicked. The button was given the full width of the wider animation, but the mouse input was bounded so that the user can't click beside the normal button image to click on the button.

Index

Copyright (C) 2008-2009 Steven Fletcher. All rights reserved.