Design Patterns - SPLessons
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 [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]

shape 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

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.