wood burning stoves 2.0*
The moose likes OO, Patterns, UML and Refactoring and the fly likes Building a Decorator Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "Building a Decorator Question" Watch "Building a Decorator Question" New topic
Author

Building a Decorator Question

Kristian Paul
Greenhorn

Joined: Jan 12, 2006
Posts: 4
In the head first design patterns book, it mentions when using the decorator pattern, the builder pattern or factory is used for construction. Can someone pls show me an example how this would work?

Thank You
B.Sathish
Ranch Hand

Joined: Aug 18, 2005
Posts: 372
In the decorator pattern, you will usually have lot of instantiation to do. Take this for example,

public class BeverageStore
{
public void processBeverage()
{
Beverage beverage = new DarkRoast(description);
beverage = new Mocha(beverage);
beverage = new Whip(beverage);

//other code that uses the decorated beverage
}
}

This object instantiation can be encapsulated in a factory method

public abstract class BeverageStore
{
public void processBeverage()
{
abstract Beverage createBeverage();
void useBeverage()
{
Beverage beverage = createBeverage();
// use the beverage for processing
}
}
}

public class DarkRoastStore extends BeverageStore
{
public Beverage createBeverage()
{
Beverage beverage = new DarkRoast(description);
beverage = new Mocha(beverage);
beverage = new Whip(beverage);
return beverage;
}
}

public class HouseBlendStore extends BeverageStore
{
public Beverage createBeverage()
{
Beverage beverage = new HouseBlend(description);
beverage = new Soy(beverage);
beverage = new Mocha(beverage);
return beverage;
}
}

In this way, you have cleanly encapsulated the object instantiations needed for decoration. The advantage is that your client BeverageStore is now dependent on an interface Beverage and not on concrete beverage classes as before. You can have different subclasses to create different beverages. If there is any change in the way a beverate needs to be created, like you need to have an extra decorator for HouseBlend, you have only once place to change. On the other hand, if you had created the houseblend in many places, you'll have to change that code everywhere whenever the instantiation of the houseblend changes in some way, like adding new decorators. Thus, you prevent your object creation code from running wild by cleanly encapsulating it in the subclasses. Here, we have used the Factory Method pattern along with the decorator pattern.

hth
Kristian Paul
Greenhorn

Joined: Jan 12, 2006
Posts: 4
Perfect, thanks!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Building a Decorator Question
 
Similar Threads
decorator pattern from HFDP
List of Patterns used in Java SE
Decorator Pattern ??
Decorator design pattern
Is this a design pattern?