What will you do if you want to add more features to an existing class without changing it? The simplest answer would be to extends it, another good answer for this is to do like what the Composite Pattern does – to make a wrapper of the class. But for a better answer, we should use both of them with the Decorator Pattern.
What is Decorator Pattern?
To make it simple: the Decorator Pattern is one of the Structural Patterns that utilizes the combination of Extending and Wrapping a class in a standard way to add more features to a component.
And for an in-depth design, please see the example below:
As you can see in the picture, there are three famous Text Editor that everybody knows: Notepad, Notepad++ and Word.
- Notepad is the simplest text editor, it can create new text file and save them, everything is in plain-text only.
- Notepad++ supports user by giving format various type of text file: .java, .php, .html (with color and folding), and it can save file with various file format too.
- And finally Word is the biggest text editor here, with it you can edit and publish press: RichText format, picture, table, calculation and more are supported, save file in .DOC and .HTML and more if you need to.
That’s for the story about three characters we will use in the demonstration.
Decorator Pattern Example
First let’s see how we will define a standard for Notepad or Notepad++ or Word or whatever text editor must conform to: The TextEditor interface.
package net.searchdaily.java.design.pattern.decorator;
/**
* Decorator Pattern Tutorial by http://java.searchdaily.net.
*
* @author namnvhue
*
*/
public interface TextEditor {
public String create(); // create text file
public String edit(); // edit the file
public String save(); // save the change to hard disk
}
And now we will create a decorator which wrapped the TextEditor to enhance it feature and also implements TextEditor interface to conform standard.
package net.searchdaily.java.design.pattern.decorator;
/**
* Decorator Pattern Tutorial by http://java.searchdaily.net.
*
* @author namnvhue
*
*/
public abstract class TextEditorDecorator implements TextEditor {
protected TextEditor enhancedTextEditor; // will support more features later
public TextEditorDecorator(TextEditor textEditor) {
this.enhancedTextEditor = textEditor;
}
@Override
public String create() {
return this.enhancedTextEditor.create();
}
@Override
public String edit() {
return this.enhancedTextEditor.edit();
}
@Override
public String save() {
return this.enhancedTextEditor.save();
}
}
Basic function like create(), edit() or save() we will ask the basic TextEditor to do it ![]()