This works by adding a new decorator class (ActorDecorator) that wraps the original class (Actor). This wrapping is typically achieved by passing the original object as a parameter to the constructor of the decorator when it is created. The decorator (DancingActorDecorator or SingingActorDecorator) implements the new functionality (Singing or Dancing), but for functionality that is not new (Acting), the original class(SimpleActor) is used. The decorating class (DancingActorDecorator or SingingActorDecorator) must have the same interface (Actor) as the original class (SimpleActor).
A simple example will illustrate the pattern more clearly.
// Actor interface
interface Actor {
public void act();
public String getDescription();
}
// implementation of a simple actor without any extra skills.
class SimpleActor implements Actor {
public void act() {
// Acting implementation
}
public String getDescription() {
return "I can act.";
}
}
// abstract Decorator class
abstract class ActorDecorator implements Actor {
protected Actor decoratedActor;
public ActorDecorator(Actor decoratedActor) {
this.decoratedActor = decoratedActor;
}
}
// the first concrete decorator which adds dancing functionality
class DancingActorDecorator extends ActorDecorator {
public DancingActorDecorator(Actor decoratedActor) {
super(decoratedActor);
}
public void act() {
dance();
decoratedActor.act();
}
private void dance() {
// Dancing implementation
}
public String getDescription() {
return decoratedActor.getDescription() + " I can dance too.";
}
}
// the second concrete decorator which adds singing functionality
class SingingActorDecorator extends ActorDecorator {
public SingingActorDecorator(Actor decoratedActor) {
super(decoratedActor);
}
public void act() {
sing();
decoratedActor.act();
}
private void sing() {
// Singing implementation
}
public String getDescription() {
return decoratedActor.getDescription() + " I can sing too.";
}
}
// test class
public class DecoratorPatternTest {
public static void main(String[] args) {
// create a decorated Actor with singing and dancing skills.
Actor decoratedActor = new DancingActorDecorator(
new SingingActorDecorator(new SimpleActor()));
// print the Actor's description
System.out.println(decoratedActor.getDescription());
}
}

No comments:
Post a Comment