Object Decorator Pattern

OK, so a short break done and I had a nice time , thank you for asking.  The next section on the Udacity Object Oriented JavaScript course was about Object Decorator Pattern and code reuse.

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.

Decorators provide flexibility to statically typed languages by allowing runtime changes as opposed to inheritance which takes place at compile time. JavaScript, however, is a dynamic language and the ability to extend an object at runtime is baked into the language itself.

For this reason, the Decorator pattern is less relevant to JavaScript developers. In JavaScript the Extend and Mixing patterns subsume the Decorator pattern.


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

Leave a Reply

Your email address will not be published. Required fields are marked *