Tutorial: Avoid Excessive Subclassing with the Decorator Design Pattern:

Wrap It Up (I'll Take It)

With apologies to The Fabulous Thunderbirds, the Decorator design pattern "wraps it up" by allowing a Decorator class to wrap itself around an existing object. In the lab employee example, the decorators are ComputerSecurityOfficer, BloodDriveCanvasser, and SafetyCaptain. They wrap themselves around the concrete Employee objects (PrincipleInvestigator, ResearchTechnician, and AdministrativeAssistant) to dynamically add additional roles and responsibilities. These wrappers don't modify any of the original classes, so everything can take place at runtime. This satisfies another important design principle (quoted from Bertrand Meyer's Object-Oriented Software Construction):

"Classes should be open for extension, but closed for modification."

In other words, it's all right to add new behavior dynamically, but it is not alright to modify an existing component class.

The Decorator design pattern is typically used in GUI applications. It's used to decorate simple buttons, dialog boxes, and other GUI components with additional borders or with other GUI components. But, as you've seen in this article, you can use this design pattern in other ways.

Use of Decorators in the Java API

The Java API makes use of the Decorator design pattern with the Reader and Writer classes. For example, in the code:
FileReader file = new FileReader("barry.txt");
BufferedReader buffered = new BufferedReader(reader);
you're decorating a FileReader with the BufferedReader class.

The Pros and the Cons

Use of the Decorator design pattern can have both good and bad consequences:
  • Making Your Code More Flexible: Decorating is more flexible than plain, old static inheritance. This is, of course, a major benefit. Decorator patterns help you avoid all of those nasty, convoluted objects with potentially long class names—names like AdminstrativeAssistantAndBloodDriveCanvasser. This pattern is especially handy because you can add any number of decorators to a particular component.
  • Keeping It Simple: When you use the Decorator design pattern, you don't have to write complex classes that consider every possible scenario (e.g., every combination of employee roles). You design a simple, abstract class (such as Employee) and then decorate the class as necessary. You can also develop new concrete decorators without disturbing the original design of the application.
  • The Identity Crisis: Decorators wrap themselves around components. But an original component isn't the same as a decorated component. You need to be careful about object identity whenever you refer to one of the decorated components. For example, when you decorate a PrincipleInvestigator object with the ComputerSecurityOfficer type, you dynamically change the object's behavior and identity. If some client code expects that object to behave strictly as a PrincipleInvestigator, then the client may be in for a big (painful) surprise. This danger is inherent in any kind of dynamic type manipulation—with or without the Decorator design pattern.
  • Object Critters: Even with the Decorator pattern, you can still have an overabundance of classes, especially the concrete decorator classes. But, each of these classes is short and sweet. Each concrete decorator class describes only one thing. It describes the way in which the class decorates a component object.

In the object-oriented programming paradigm, programmers model real-life objects. The Decorator is a very versatile pattern for the modeling of real-life objects.

Resources

About the Authors

Barry Burd is a professor in the Department of Mathematics and Computer Science at Drew University in Madison, New Jersey. When he's not lecturing at Drew University, Dr. Burd leads training courses for professional programmers in business and industry. He has lectured at conferences in America, Europe, Australia and Asia. He is the author of several articles and books, including Java 2 For Dummies and Eclipse For Dummies, both published by Wiley.

Michael P. Redlich is a Senior Research Technician (formerly a Systems Analyst) at ExxonMobil Research & Engineering, Co. in Clinton, New Jersey with extensive experience in developing custom Web and scientific laboratory applications. Mike also has experience as a Technical Support Engineer for Ai-Logix, Inc. where he developed computer telephony applications. He has a Bachelor of Science in Computer Science from Rutgers University. Mike's computing experience includes computer security, relational database design and development, object-oriented design and analysis, C/C++, Java, Visual Basic, FORTRAN, Pascal, MATLAB, HTML, XML, ASP, VBScript, and JavaScript in both the PC and UNIX environments.

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.