Decorator Design Pattern: The Decorator design pattern adds additional responsibilities to an object dynamically without affecting other objects or existing objects. It is like a wrapper on another object.
In other words, The decorator pattern is used to extend (decorate) the functionality of a certain object statically, or dynamically.
The decorator pattern is an alternative to subclassing. We can write a subclass by extending a class and add behavior at compile time, and the change affects all object instances of the original class.
But we can achieve this same behavior without extending a class and using a decorator class, since decorating can provide new behavior at run-time for individual objects.
Lets take an example to understand it.
Problem: We need to read a text file and display its content on screen. So we can write a InputReader class which will take a file as input and read the text file and display the content.
- The given file has text with lots of extra white spaces, So using this InputReader how we can read the file and display the text by removing extra white spaces. i.e "abc xyz" shoud be displayed as "abc xyz".
- The given text file is an encrypted file and before displaying the text on screen it has to be decrypt. So using the InputReader class how we can achieve this?....