Τετάρτη 26 Ιανουαρίου 2022

Decorator pattern

  • What problem does Decorator pattern solve?



Suppose we have a hierarchy of shape objects:





At some point we may need a Circle with a red border layout dynamically.

Is it correct to create another concrete class statically?




No, we would duplicate our code, for only one little adjustment of a red border.

In addition, we can't have an extra interface for our new requirement, because all Components will have to implement the red border.

We also want a dynamic change only. 




  • How does Decorator pattern solve this?



The decorator pattern allows you to alter behavior dynamically, without affecting other objects of the same type.


We create an extra concrete class that 
- implements Component
- takes our to-be-decorated object as a constructor argument
- has generic functionality (add red border) for all Component objects
- has sole responsibility to add a red border





Code:


Use:

Only circle2 with have a red border


Note that ComponentWithRedBorder delegates execution to the original Component object, after having decorated it.






 



Δεν υπάρχουν σχόλια:

Δημοσίευση σχολίου

What may be missing, or could get better?