Decorator pattern adds additional functionalities to a object dynamically without disturbing the other instances. The sub classes can be extended easily using Decorator pattern. Decorator pattern is a type of structural pattern and is also known as "wrapper".
Advantages
Provides much flexibility than static class.
Abstract class or interface is used for composition.
Coding is simplified.
Conceptual
figure
Component : The responsibilities for interface objects can be added dynamically.
ConcreteComponent : Concrete Component is used to define an object to which additional responsibilities can be added.
Decorator : Maintains a reference to a Component object and defines a interface that conforms to Component's interface.
Concrete Decorator : Concrete Decorator is used to extend the functionality of the component by adding the state or behavior.
Examples
Defining an interface Bike
[java]
public interface Bike
{
public void assemble();
}[/java]
Creating a class BasicBike which implements the interface Bike.
[java]
class BasicBike implements Bike
{
public void assemble()//overrides the interface method
{
System.out.print("Basic Bike.");
}
}[/java]
Creating a class BikeDecorator which implements the interface Bike.
[java]
class BikeDecorator implements Bike
{
protected Bike byk;
public BikeDecorator(Bike c)
{
this.bike=c;
}
public void assemble()//overrides the interface method
{
this.bike.assemble();
}
}[/java]
Creating a class SportsBike which extends the BikeDecorator class.
[java]
class SportsBike extends BikeDecorator
{
public SportsBike(Bike c)
{
super(c);
}
public void assemble()//overrides the interface method
{
bike.assemble();
System.out.print(" Adding features of Sports Byke.");
}
}[/java]
Creating a class LuxuryBike which extends the BikeDecorator class.
[java]
class LuxuryBike extends BikeDecorator
{
public LuxuryBike(Bike c)
{
super(c);
}
public void assemble()//overrides the interface method
{
bike.assemble();
System.out.print(" Adding features of Luxury Byke.");
}
}[/java]
Creating a DecoratorPatternTest.
[java]
class DecoratorPatternTest {
public static void main(String[] args) {
Bike sportsBike = new SportsBike(new BasicByke());
sportsBike.assemble();
System.out.println("\n*****");
Bike sportsLuxuryBike = new SportsBike(new LuxuryBike(new BasicBike()));
sportsLuxuryBike.assemble();
}
}[/java]
Output
Result will be as follows.
[java]Basic Bike. Adding features of Sports Bike.
*****
Basic Bike. Adding features of Luxury Bike. Adding features of Sports Bike.[/java]
Summary
Key Points
Additional features can be added to an object dynamically by using the Decorator Pattern.
Additional features can be removed easily by using Decorator Pattern.
Decorator Pattern is mostly used in java IOclasses.