Attach additional responsibilities to an object dynamically. DecoratorsSkip to Sample Code
provide a flexible alternative to subclassing for extending functionality.
Usage Scenarios
- Add responsibilities to individual objects dynamically and transparently, that is, without affecting other objects.
- Be able to withdraw responsibilities
For example: The java.util.Collections.unmodifiableCollection(Collection) removies the ability to change a given collection by wrapping it with a decorator that throws an UnSupportedException when you try to modify the Collection. - When extension by subclassing is impractical, such as when a large number of independent extensions produce an explosion of subclasses to support every combination. Or a class is unavailable for subclassing.
Here is the UML diagram of the Decorator pattern followed by a description of the various involved components.
- Component: Defines the interface for objects that can have responsibilities added to them dynamically.
- ConcreteComponent: Defines an object to which additional responsibilities can be attached.
- Decorator: maintains a reference to a Component object and defines an interface that conforms to Component's interface.
- ConcreteDecorator: adds responsibilities to the component.
The following is sample implementation of the Decorator pattern in Java.
- The Component Interface
package decorator;
public interface IComponent {
public void doStuff();
}IComponent.java - The Concrete Component
package decorator;
public class Component implements IComponent{
public void doStuff() {
System.out.println("Do Suff");
}
}Component.java - The Decorator
package decorator;
public interface Decorator extends IComponent {
public void addedBehavior();
}Decorator.java Note: The decorator interface has to conform to the component interface, hence it extends IComponent. - The Concrete Decorator
package decorator;
public class ConcreteDecorator implements Decorator {
IComponent component;
public ConcreteDecorator(IComponent component) {
super();
this.component = component;
}
public void addedBehavior() {
System.out.println("Decorator does some stuff too");
}
public void doStuff() {
component.doStuff();
addedBehavior();
}
}ConcreteDecorator.java - The Client
import decorator.*;
public class Client {
public static void main(String[] args) {
IComponent comp = new Component();
Decorator decorator = new ConcreteDecorator(comp);
decorator.doStuff();
}
}Client.java
No comments:
Post a Comment