Decorator pattern is technique where existing object behavior to be added dynamically or in another word when we change object behavior at runtime which is also called in java runtime polymorphism.
This decorator pattern is another approach to sub classing. When we do sub classing means it adds behavior at compile time and change takes affects to all instances of original class. Decorating object provides new behavior of the object at runtime of each individual objects and this modification or difference becomes important when we have several independent techniques of extending existing functionality of the objects. For example Input/output streams implementations in java framework incorporate decorator pattern.
Below example will show you how to use decorator pattern (We will use apartment scenario)
- Apartment Interface
- Implementation of a simple Apartment without adding anything
- Below abstract class implements Apartment interface and adds one abstract function to decorate apartment
- Now create concrete class FurnishedApartment by extending Apartment Decorator to decorate apartment
- Below is test program:
- That’s it. Below is list of all design patterns link:
- Chain of Responsibility
- Template Method