Decorator design pattern is used to modify the functionality of an object at runtime. At the same time other instances of the same class will not be affected by this, so individual object gets the modified behavior. Decorator design pattern is one of the structural design pattern (such as Adapter Pattern, Bridge Pattern, Composite Pattern) and uses abstract classes or interface with composition to implement.
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 runtime - 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. But if we want to get a car at runtime that has both the features of sports car and luxury car, then the implementation gets complex and if further more we want to specify which features should be added first, it gets even more complex. Now imagine if we have ten different kind of cars, the implementation logic using inheritance and composition will be impossible to manage. To solve this kind of programming situation, we apply decorator pattern in java. We need to have following types to implement decorator design pattern.
Component Interface - The interface or abstract class defining the methods that will be implemented. In our case Car
will be the component interface.
package com.journaldev.design.decorator;
public interface Car {
public void assemble();
}
Component Implementation - The basic implementation of the component interface. We can have BasicCar
class as our component implementation.
package com.journaldev.design.decorator;
public class BasicCar implements Car {
@Override
public void assemble() {
System.out.print("Basic Car.");
}
}
Decorator - Decorator class implements the component interface and it has a HAS-A relationship with the component interface. The component variable should be accessible to the child decorator classes, so we will make this variable protected.
package com.journaldev.design.decorator;
public class CarDecorator implements Car {
protected Car car;
public CarDecorator(Car c){
this.car=c;
}
@Override
public void assemble() {
this.car.assemble();
}
}
Concrete Decorators - Extending the base decorator functionality and modifying the component behavior accordingly. We can have concrete decorator classes as LuxuryCar
and SportsCar
.
package com.journaldev.design.decorator;
public class SportsCar extends CarDecorator {
public SportsCar(Car c) {
super(c);
}
@Override
public void assemble(){
super.assemble();
System.out.print(" Adding features of Sports Car.");
}
}
package com.journaldev.design.decorator;
public class LuxuryCar extends CarDecorator {
public LuxuryCar(Car c) {
super(c);
}
@Override
public void assemble(){
super.assemble();
System.out.print(" Adding features of Luxury Car.");
}
}
package com.journaldev.design.test;
import com.journaldev.design.decorator.BasicCar;
import com.journaldev.design.decorator.Car;
import com.journaldev.design.decorator.LuxuryCar;
import com.journaldev.design.decorator.SportsCar;
public class DecoratorPatternTest {
public static void main(String[] args) {
Car sportsCar = new SportsCar(new BasicCar());
sportsCar.assemble();
System.out.println("\n*****");
Car sportsLuxuryCar = new SportsCar(new LuxuryCar(new BasicCar()));
sportsLuxuryCar.assemble();
}
}
Notice that client program can create different kinds of Object at runtime and they can specify the order of execution too. Output of above test program is:
Basic Car. Adding features of Sports Car.
*****
Basic Car. Adding features of Luxury Car. Adding features of Sports Car.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
what is the user of CarDecorator. We can ignore this class and achieve the same output
- satyasiba biswal
Great concise and very clear explanation. Thanks!
- alex
This is a great example, thank you. If I may suggest, I believe it would be more didactic if you use Options instead of Cars for the Decorator related classes, this way it’s easier to understand that the final Car will be the assemble of different options (or features).
- Andre
Another example https://github.com/radhikapatel4391/CS680/tree/master/Homework3/src/hw3 Very nice tutorial point to point and simple easy to understand.
- Radhikabahen Patel
DVDPlayer example… https://github.com/radhikapatel4391/CS680/tree/master/Homework3/src/hw3 Nice blog…
- Radhikabahen Patel
Very helpful information, I’m glad you shared it with people like us who are learning it
- Divyansh Anand
Hello,everyone! I have Monster(main class) and some Concrete classes(, like Troll,Vampire). Also I have MonsterDecorators,like Club,Sword and etc. EXAMPLE: Monster troll = new Troll(); troll.getAttackPower() // 30 troll.attack(); // The troll tries to grab you! troll.fleeBattle(); // The troll shrieks in horror and runs away! -->change the behavior of the simple troll by adding a decorator troll = new ClubDecorator(troll); troll.getAttackPower() // 42 troll.attack(); // The troll tries to grab you! The troll swings at you with a club! troll.fleeBattle(); // The troll shrieks in horror and runs away! And loses his club while running! so after fleeBattle method, how troll can be just Troll, without any decorators?
- Farukh
Ah ha … This is a Junit rule . Statement.apply( (Statement) base ) . ahh :(… I havent been outside for a while
- Mark Schumacher
How to get the features of Luxury Car separately if I need them for another car at my home. I assume the same scenario is for Dosa where you can get plain dosa, dosa with masala and dosa with chutney. So masala and chutney classes extend DosaDecorator. PlainDosa class and DosaDecorator class implements Dosa interface. Now what if i want extra chutney (means only chutney separately) ? Thanks in advance.
- Arun Singh
How to print only Luxury Car? Thanks
- Arun Singh