I have in the past come across having to do things again and again again and realising that its the same code being used every time. So rather than rewriting the code again an again again why not reuse the code as a function again and again and again?
The formal definition for a detractor – Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
The Decorator pattern extends (decorates) an object’s behaviour dynamically. The ability to add new behaviour at runtime is accomplished by a Decorator object which ‘wraps itself’ around the original object. Multiple decorators can add or override functionality to the original object.
An example of a decorator is security management where business objects are given additional access to privileged information depending on the privileges of the authenticated user. For example, an HR manager gets to work with an employee object that has appended (i.e. is decorated with) the employee’s salary record so that salary information can be viewed.
So here we have:
- Client — In sample code: the run() function
- maintains a reference to the decorated Component
- Component — In sample code: User
- object to which additional functionality is added
- Decorator — In sample code: DecoratedUser
- ‘wraps around’ Component by maintaining a reference to it
- defines an interface that conforms to Component’s interface
- implements the additional functionality (addedMembers in diagram)
So remember the decorator pattern is used to add some functionality to an object which already has some functionality in it at that point.
Good to be back, welcome to May and see you soon