Zum Inhalt springen

What is Decorator Design Pattern?

โ‰๏ธ ๐‘ด๐’๐’•๐’Š๐’—๐’‚๐’•๐’Š๐’๐’
Have you ever tried to add responsibility to an object dynamically? Decorator provides a flexible alternative to subclassing. It is known as wrapper.

Image description

๐ŸŒ ๐‘น๐’†๐’‚๐’-๐‘พ๐’๐’“๐’๐’… ๐‘บ๐’„๐’†๐’๐’‚๐’“๐’Š๐’
Imagine, there is a graphical component that lets you add properties such as: border, scroll bar, and so forth. One way to implement it is using inheritance, but it is not flexible. Since, the border is added statically, and a client cannot control how and when to decorate a component with a border. How can we add the border in a flexible way?

๐ŸŽฏ ๐’๐จ๐ฅ๐ฎ๐ญ๐ข๐จ๐ง โ€” ๐ƒ๐„๐‚๐Ž๐‘๐€๐“๐Ž๐‘ ๐๐š๐ญ๐ญ๐ž๐ซ๐ง
Decorator encloses the component in another object that adds the border. The decorator conforms to the interface of the component it decorates. So, its presence is transparent to clients. The decorator forwards the request to the component and it does some actions such as adding a boarder before or after forwarding.

Image description

๐Ÿง  ๐–๐ก๐ž๐ง ๐ญ๐จ ๐”๐ฌ๐ž
โœ”๏ธAdd a functionality to an object dynamically and transparently with zero effects for other objects.
โœ”๏ธ For functionalities which can be removed.
โœ”๏ธWhen we want to extend a functionality with subclassing, but it is impossible, due to the explosion of subclasses.

๐Ÿ’Ž ๐‘น๐’†๐’๐’‚๐’•๐’†๐’… ๐‘ท๐’‚๐’•๐’•๐’†๐’“๐’๐’”:
โ—พ ๐€๐๐š๐ฉ๐ญ๐ž๐ซ: the adapter grants an object a new interface, but the decorator changes the responsibilities of an object.

โ—พ๐‚๐จ๐ฆ๐ฉ๐จ๐ฌ๐ข๐ญ๐ž: we can consider the decorator as a decadent version of composite since it has only one component.

โ—พ๐’๐ญ๐ซ๐š๐ญ๐ž๐ ๐ฒ: the decorator changes the skin of an object while the strategy modifies mechanism.

๐Ÿ“‚ ๐‚๐จ๐๐ž ๐„๐ฑ๐š๐ฆ๐ฉ๐ฅ๐ž
๐Ÿ‘‰ GitHub – https://lnkd.in/dv_YvFTd

โ“Have you ever used the ๐ƒ๐„๐‚๐Ž๐‘๐€๐“๐Ž๐‘ Pattern in your projects?

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht verรถffentlicht. Erforderliche Felder sind mit * markiert