Decorator Design Pattern
Decorator design pattern is one of the famous structural design pattern. Decorator design pattern is used to modify the functionality of an object at run time. At the same time other instances of the same class will not be affected by this, so individual object gets the modified behavior. The Decorator design pattern attach additional responsibilities to an object dynamically.It is wrap up at another object.It will extend functionality of object without affecting any other object.
We use inheritance or composition to extend the behavior of an object but this is done at compile time and its applicable to all the instances of the class. We can’t add any new functionality of remove any existing behavior at run time – this is when Decorator pattern comes into picture.
Suppose we want to implement different kinds of cars – we can create interface Car to define the assemble method and then we can have a Basic car, further more we can extend it to Sports car and Luxury Car. The implementation hierarchy will look like below image.
Component Interface
package com.ashok.designpatterns.decorator; /** * * @author ashok.mariyala * */ public interface Car { public void assemble(); }
Component Implementation
package com.ashok.designpatterns.decorator; /** * * @author ashok.mariyala * */ public class BasicCar implements Car { @Override public void assemble() { System.out.println("Inside Basic Car."); } }
Decorator
package com.ashok.designpatterns.decorator; /** * * @author ashok.mariyala * */ public class CarDecorator implements Car { protected Car car; public CarDecorator(Car c) { this.car = c; } @Override public void assemble() { this.car.assemble(); } }
Concrete Decorators
package com.ashok.designpatterns.decorator; /** * * @author ashok.mariyala * */ public class SportsCar extends CarDecorator { public SportsCar(Car c) { super(c); } @Override public void assemble() { super.assemble(); System.out.println(" Adding features of Sports Car."); } } package com.ashok.designpatterns.decorator; public class LuxuryCar extends CarDecorator { public LuxuryCar(Car c) { super(c); } @Override public void assemble() { super.assemble(); System.out.println(" Adding features of Luxury Car."); } }
Test Decorator Pattern
package com.ashok.designpatterns.decorator; /** * * @author ashok.mariyala * */ public class TestDecoratorPattern { public static void main(String[] args) { Car sportsCar = new SportsCar(new BasicCar()); sportsCar.assemble(); Car sportsLuxuryCar = new SportsCar(new LuxuryCar(new BasicCar())); sportsLuxuryCar.assemble(); } } Output Inside Basic Car. Adding features of Sports Car. Inside Basic Car. Adding features of Luxury Car. Adding features of Sports Car