Monday, February 28, 2011

Decorator Pattern

The Decorator Pattern is used for adding additional functionality to a particular object as opposed to a class of objects. It is easy to add functionality to an entire class of objects by subclassing an object, but it is impossible to extend a single object this way. With the Decorator Pattern, you can add functionality to a single object and leave others like it unmodified.
A Decorator, also known as a Wrapper, is an object that has an interface identical to an object that it contains. Any calls that the decorator gets, it relays to the object that it contains, and adds its own functionality along the way, either before or after the call. This gives you a lot of flexibility, since you can change what the decorator does at runtime, as opposed to having the change be static and determined at compile time by subclassing. Since a Decorator complies with the interface that the object that it contains, the Decorator is indistinguishable from the object that it contains.  That is, a Decorator is a concrete instance of the abstract class, and thus is indistinguishable from any other concrete instance, including other decorators.   This can be used to great advantage, as you can recursively nest decorators without any other objects being able to tell the difference, allowing a near infinite amount of customization.

Decorators add the ability to dynamically alter the behavior of an object because a decorator can be added or removed from an object without the client realizing that anything changed.  It is a good idea to use a Decorator in a situation where you want to change the behaviour of an object repeatedly (by adding and subtracting functionality) during runtime.    
The dynamic behavior modification capability also means that decorators are useful for adapting objects to new situations without re-writing the original object's code.
The code for a decorator would something like this:
void doStuff() { 

// any pre-processing code goes here.
   aComponent.doStuff() // delegate to the decoree
// any post-processing code goes here
}



Note that the decorator can opt to not delegate to the decoree, if, for instance, some condition was not met.
A very nice example of decorators is Java's I/O stream implementation.
 

Example


Component


public abstract class Breakfast {

String description = "Unknown Breakfast";

public String getDescription() {
return description;
}
public abstract double cost();
}

Concrete Component

The ConcreteComponent is the object we’re going to dynamically add new behavior to. It extends Component.

public class Dosa extends Breakfast{

public Dosa() {
description = "Dosa";
}

public double cost(){
return 12.50;
}
}

 

Another Component:

 


public class Idli extends Breakfast{

public Idli() {
description = "Idli";
}
public double cost(){
return 10.50;
}
}

Decorator

Each decorator HAS-A (wraps) a component, which means the decorator has an instance variable that holds a reference to a component.
Decorators implement the same interface or abstract class as the component they are going to decorate.


// Decorator
public abstract class Decorator extends Breakfast{

public abstract String getDescription();

}


Concrete Decorator:
The ConcreteDecorator has an instance variable for the thing it decorates (the Component the Decorator wraps).

public class MasalaDosaDecorator extends Decorator{

Breakfast breakfast;

public MasalaDosaDecorator(Breakfast breakfast){
this.breakfast = breakfast;
}

public String getDescription(){
return breakfast.getDescription()+" ,its MasalaDosa";
}

public double cost(){
return breakfast.cost() + 5.50;
}
}


Now have another concrete decorator, say OnionDosaDecorator:



public class OnionDosaDecorator extends Decorator{

Breakfast breakfast;

public OnionDosaDecorator(Breakfast breakfast){
this.breakfast = breakfast;
}

public String getDescription(){
return breakfast.getDescription()+" , its OnionDosa";
}

public double cost(){
return breakfast.cost() + 3.50;
}
}


Decorator Demo : Time to order dosa.


Now its time to have our menu to be served, with main function.



public class BreakfastMenu {

public static void main(String[] args) {

// without adding decorators
Breakfast menu1 = new Dosa();
System.out.println(menu1.getDescription() +" Rs. "+menu1.cost());


//adding decorators
Breakfast menu2 = new MasalaDosaDecorator(new OnionDosaDecorator(new Dosa()));
System.out.println(menu2.getDescription() +" Rs. "+menu2.cost());

Breakfast menu3 = new MasalaDosaDecorator(new Dosa());
System.out.println(menu3.getDescription() +" Rs. "+menu3.cost());
}
}

Decorators can extend the state of the component.
Decorators can add new methods. however new behavior is typically added by doing computation before or after an existing method in the component.
Inheritance is one form of extension, but not necessarily the best way to achieve flexibility in our 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 runtime.
The Decorator Pattern provides an alternative to subclassing for extending behavior.
The Decorator Pattern involves a set of decorator classes that are used to wrap concrete components.
Decorator classes mirror the type of the components they decorate. (In fact, they are the same type as the components they decorate, either through inheritance or interface implementation.)
Decorators change the behavior of their components by adding new functionality before and/or after (or even in 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.
Adapter provides a different interface to its subject.Proxy provides the same interface.Decorator provides an enhanced interface.[GoF, p216]
Adapter changes the object's interface,Decorator enhances an object's responsibilities.Decorator is thus more transparent to the client.As a consequence,Decorator supports recursive composition,which isnt possible with pure Adapters.[GoF, p149]
Composite and Decorator have similar structure diagrams,reflecting the fact that both rely on recursive composition to organize an open-ended number of objects.[GoF, p219]
A Decorator can be viewed as a degenerate Composite with only one component.However a decorator adds additional responsibilities-it isnt intended for object aggregation.[GoF, p184]
Decorator is designed to let you add responsibilites to objects without subclassing.Composite's focus is not an embellishment but on representation.These intents are distinct but complementary.Consequently Composite and Decorator are often used in concert. [GoF, p220]
Decorator lets us change the skin of an object.Strategy lets us change the guts.[GoF, p184]
Decorator and Proxy have diff purposes but similar structures.Both describe how to provide a level of indirection to another object,and the implementations keep a reference to the object to which they forward requests.[GoF, p220]

Disadvantage



Only disadvantage is code maintenance can be a problem as it provides the system with a lot of similar looking small objects(each decorator).

No comments:

Post a Comment

Chitika