Design Patterns - SPLessons

Decorator Pattern

Chapter 14

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Decorator Pattern

Decorator Pattern

shape Description

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”.

shape Advantages

  • Provides much flexibility than static class.
  • Abstract class or interface is used for composition.
  • Coding is simplified.

shape Conceptual
figure

shape Examples

Defining an interface Bike

public interface Bike
{
public void assemble();
}

Creating a class BasicBike which implements the interface Bike.

class BasicBike implements Bike
{
public void assemble()//overrides the interface method
{
System.out.print("Basic Bike.");
}
}

Creating a class BikeDecorator which implements the interface Bike.

class BikeDecorator implements Bike
{
protected Bike byk;
public BikeDecorator(Bike c)
{
this.bike=c;
}
public void assemble()//overrides the interface method
{
this.bike.assemble();
}
}

Creating a class SportsBike which extends the BikeDecorator class.

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.");
}
}

Creating a class LuxuryBike which extends the BikeDecorator class.

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.");
}
}

Creating a DecoratorPatternTest.

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();
}
}

shape Output

Result will be as follows.

Basic Bike. Adding features of Sports Bike.
*****
Basic Bike. Adding features of Luxury Bike. Adding features of Sports Bike.

Summary

shape 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.