Decorator Design Pattern
Decorator pattern allows a user to add new functionality to an existing object
without altering its structure.
Means that Decorator design pattern allows us to dynamically add
functionality and behavior to an object without affecting the behavior of other
existing objects within the same class.
Because it allows a user to add new functionality to an existing object without
altering its structure. So, there is no change to the original class.
The decorator design pattern is a structural pattern, which provides a wrapper
to the existing class.
It uses abstract classes or interfaces with the composition to implement the
wrapper.
Decorator design patterns create decorator classes, which wrap the original
class and supply additional functionality by keeping the class methods’
signature unchanged.
Decorator design patterns are most frequently used for applying single
responsibility principles since we divide the functionality into classes with
unique areas of concern.
The decorator design pattern is structurally almost like the chain of
responsibility pattern.
Procedure:
1. Create an interface.
2. Create concrete classes implementing the same interface.
3. Create an abstract decorator class implementing the above same
interface.
4. Create a concrete decorator class extending the above abstract
decorator class.
5. Now use the concrete decorator class created above to decorate
interface objects.
6. Lastly, verify the output
Implementation:
We’re going to create a Shape interface and concrete classes implementing the
Shape interface. We will then create an abstract decorator class
ShapeDecorator implementing the Shape interface and having the Shape object
as its instance variable.
1. ‘Shape’ is the name of the interface
2. ‘Rectangle’ class and ‘Circle’ class will be concrete classes
implementing the ‘Shape’ interface.
3. ‘ShapeDecorator’ is our abstract decorator class implementing the
same ‘Shape’ interface.
4. RedShapeDecorator is a concrete class implementing
ShapeDecorator.
5. DecoratorPatternDemo, our demo class will use RedShapeDecorator
to decorate Shape objects.
Acknowledge: Thanks to geeksforgeeks for the content of design pattern