A Simple Decorator Pattern Example
(Page 1 of 4 )
In this second part of a six-part series on the Decorator design pattern, you will walk through an example that shows you the minimum number of components required to create it. This article is excerpted from chapter four of
ActionScript 3.0 Design Patterns Object Oriented Programming Techniques, written by William B. Sanders and Chandima Cumaranatunge (O'Reilly, 2007 ISBN: 0596528469). Copyright © 2007 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.
Minimalist Abstract Decorator
To get started with the Decorator design pattern, a minimum implementation needs the following:
An abstract component
An abstract decorator
A concrete component
Concrete decorators
For the sake of clarity, two decorators will be devised so that you can better see how the structure works (and it’s closer to the model shown in Figure 4-1.) Of all the classes devised in this pattern, by far the most important is the initial abstract class modeling the component. Every other class is subclassed from this initial class.
Abstract Component Class
To begin the process of creating a Decorator design pattern, create a component. You might think of a component as an undecorated Christmas tree, or even a person deciding what to wear. It’s simple because all the added features are handled by decorators. Example 4-1 has only a single string variable that will be used to describe the component. Save the script as Component.as.
Example 4-1. Component.as
package
{
//Abstract Component in Decorator Design Pattern
//**************
//Abstract class
public class Component
{
internal var information:String;
public function getInformation():String
{
return information;
}
}
}
From this point on, all the classes will extend the Component class. Keeping in mind that the class is an abstract one—or at least is treated as one—its primary function is to establish a basic structure for the rest of the application. It contains a single variable,information, and a single getter function,getInformation(). These elements set up both the concrete components and decorations. Both components and decorations need to display information about their characteristics. A concrete Christmas tree displays information that lets you know that it’s a Christmas tree instead of another kind of object that can be decorated, such as a front yard to be decorated with gnomes and pink plastic flamingoes. Additionally, you want to be able to retrieve information, and so it has a getter function.
Next: Abstract Decorator Class >>
More Flash Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of ActionScript 3.0 Design Patterns Object Oriented Programming Techniques, written by William B. Sanders and Chandima Cumaranatunge (O'Reilly, 2007 ISBN: 0596528469). Check it out today at your favorite bookstore. Buy this book now.
|
|