The Decorator Design Pattern
The official definition of the Decorator pattern from the GoF book (Design Patterns: Elements of Reusable Object-Oriented Software, 1995, Pearson Education, Inc. Publishing as Pearson Addison Wesley) says you can, “Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.”
This pattern, also known as Wrapper, allows you to extend the core object by wrapping it in various decorator wrappers, avoiding modification of the core code. Each successive wrapper called the getDescription method of the object it wrapped and added something to it.
class ChristmasTree { public ChristmasTree() { } public String getDescription() { return "Christmas tree"; } } abstract class ChristmasTreeDecorator extends ChristmasTree { public abstract String getDescription(); } class ChristmasLight extends ChristmasTreeDecorator { private ChristmasTree christmasTree; public ChristmasLight(ChristmasTree ct) { christmasTree = ct; } public String getDescription() { return christmasTree.getDescription() + " with lights"; } } class ChristmasOrnament extends ChristmasTreeDecorator { private ChristmasTree christmasTree; public ChristmasOrnament(ChristmasTree ct) { christmasTree = ct; } public String getDescription() { return christmasTree.getDescription() + " and ornaments."; } } public class DecoratorTest { public static void main(String args[]) { ChristmasTree christmasTree = new ChristmasTree(); christmasTree = new ChristmasLight(christmasTree); christmasTree = new ChristmasOrnament(christmasTree); System.out.println("This is a " + christmasTree.getDescription()); } }
The decorator design pattern is also used in the java.io classes. These classes are designed to be “chained” or “wrapped“. You can “wrap” a BufferedReader around a FileReader or a BufferedWriter around a FileWriter, to get access to higher-level (more convenient) methods.


Tags: 



Leave a Reply