decorator - Harsh4999/Design-Patterns GitHub Wiki

Decorator

##Use

  • When we want to enhance behaviour of our existing object dynamically as and when required then we can use decorator design pattern
  • Decorator wraps an object within itself and provides same interface as the wrapped object so the client of original object doesnt need to change
  • Its an alternative to subclassing for extending functionality

##UML

  • Component = defines interface used by client
  • Concrete Component = Target object which can be decorated
  • Decorator = provides additional behaviour also maintains reference to component it implements Component but also maintains an object of it

##Implementation

  • We start by Concrete component implementation for the component
  • We define our decorator it implements the component and also needs reference to concrete component
  • In decorator methods we provide additional behaiour on top that provide by concrete compoenent
  • If we have a large state in base class as decorators then decorators may not need all state
  • Decorators supports recursive composition and so this pattern lends itself to creation of lots of small objects that add just a little bit functionality
  • They are more powerfull than inheritance
  • Decorator should act like additional skin it should not completely erase base functionality
  • Eg: BufferedOutputStream class