2. decorator pattern is a design pattern that allows behavior to be added
to an individual object, dynamically, without affecting the behavior of
other objects from the same class
What is Decorator design pattern?
3. What problems can the Decorator design
pattern solve?
• Responsibilities should be added to (and removed from) an object
dynamically at run-time.
• A flexible alternative to subclassing for extending functionality should
be provided.
4. What is the problem with subclassing ?
• With number of various functionalities that can be mixed together
Here comes the BIG problem
8. How to calculate the price of the order
interface Icalculate {
public double calculate();
}
9. How to calculate the price of the order
interface Icalculate {
public double calculate();
}
class BeefMeal:Icalculate{
..
..
public double calculate() {
return 10;
}
..
}
10. How to calculate the price of the order
interface Icalculate {
public double calculate();
}
class BeefMeal:Icalculate{
..
..
public double calculate() {
return 10;
}
..
}
class BeefMealWithLettuce : Icalculate
{
..
..
public double calulate()
{
return 10 +3 ;
}
}
15. So Where is the Trick ?
• This allows multiple decorators to be
stacked on top of each other, each time
adding a new functionality to the overridden
method(s)
16. Another Famous Example – Java IO
//First open an inputstream of it:
FileInputStream fis = new FileInputStream("/objects.gz");
//We want speed, so let's buffer it in memory:
BufferedInputStream bis = new BufferedInputStream(fis);
//The file is gzipped, so we need to ungzip it:
GzipInputStream gis = new GzipInputStream(bis);
//We need to unserialize those Java objects:
ObjectInputStream ois = new ObjectInputStream(gis);
//Now we can finally use it:
SomeObject someObject = (SomeObject)ois.readObject();