Tuesday 21 July 2015

Decorator/Wrapper Pattern

Decorator/Wrapper Pattern

DEFINED


The decorator pattern attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to sub-classing for extending functionality.

Problems to be solved.- the over use of inheritance, equals class explosion
- When you inherit behavior by sub classing, that behavior is set statically at compile time. in addition all subclasses must inherit the same behavior.

Extension - extends an object behavior dynamically at run time by using composition,


When learned - allow you to be able to give your (or someone else) objects new responsibilities with making code changes to the underlying classes.

Decorates your classes at run time using a form of object composition.
- extension at run-time rather then at compile time.
-While inheritance is powerful it doesn't lead to the most powerful designs.
 -

Open-Closed principle
-Goal is to allow classes to be easily extended to incorporate new behavior without modifying existing code. 

- There are ways of "inheriting" behavior at run-time through composition and
-IT is possible to add multiple new responsibility to objects, through this technique, including responsibilities that were not even thought of by the designer of the super class. and you don't have to touch their code.
-Code should be closed for modification, yet open for extension
-  Takes time and effort to make code this flexible

- must be careful when choosing the areas of code that need to be extend; applying the open-closed principle EVERYWHERE is wasteful and unnecessary and can lead to complex hard to understand code.

Diagrams

 


 Code Example







 

Bullet Points

  •   Inheritance is one for of extension, but not necessarily the the way way yo achieve flexibility in out designs.
  • In our designs we should allow behavior to be extended without the need to modify existing code.
  • Composition and delegation can often be used to add new behaviors at run time.
  • The Decorator pattern provides an alternative to sub-classing for extending behavior.
  • The Decorator patten involves a set of decorator classes that are used to wrap in concrete components.
  • Decorator classes mirror the type of the components they decorate. (in fact they're same type)
  • Decorators change the behavior of their components by adding new functionality before and/or  after (or even place of ) method calls to the component.
  • You can wrap a component with any number of decorators.
  • Decorators are typically transparent to the client of the component; that is, unless the client is relying on the component’s concrete type.
  • Decorators can result in many small objects in our design, and overuse can be complex




No comments:

Post a Comment