Sunday, January 10, 2010

Decorate your skills with Decorator pattern

To understand this pattern lets take a case.

Suppose a multiplex has a application to sell tickets. Now they want to sell tickets with different food/beverage option. We will try different design option one by one.

Option 1.
We sub class the base class and override the cost method. But that will result in class explosion(having lot of sub classes for each new functionality).
class MovieTicketPrice {

public double getTicketPrice(){

}
}

class MovieTicketWithCoke extends MovieTicketPrice {

public Double getTicketPrice(){
//modify the base class implementation here
}
}

but problem is we will have tons of subclasses(MovieTicketWithPopcorn, MovieTicketWithCokeAndPopcorn) of MovieTicketPrice corresponding to different options available.

Option 2.

We can have a single class and modify it

class MovieTicketPrice {
public double getTicketPrice(){}
public double addCokeSercharge(){}

}

But this design is violating basic design principle "Open for extension closed for modification". Its never a good idea to modify your already tested code to add new features.

Now lets see what we can achieve using decorator(wrapper ) pattern.

class MovieTicket{

public double getTicketPrice(){}

}

class DecoratePriceWithCoke extends MovieTicket{

MovieTicketPrice t ;
public double getTicketPrice(){
return t.getTicketPrice() + 50;
}
}

class DecoratePriceWithPopCorn extends MovieTicket{

MovieTicketPrice t ;
public double getTicketPrice(){
return t.getTicketPrice() + 80;
}
}

Now suppose we want to have an option of ticket with popcorn and coke, we don't need another class...just decorate(wrap) your movie ticket with coke and popcorn.

MovieTicket t = new MovieTicket();
t = DecoratePriceWithCoke(t);
t = DecoratePriceWithPopCorn(t);

To summerize you have to create a decorator class for new option and that can be mixed with other available option. for ex.. suppose multiplex introduce ticket with pizza. Then programmer just has to create pizza decorator class and the same can be mixed with options like pizza with coke without creating a new class PizzaWithCoke.

3 comments:

  1. Can you please elaborate on "Open for extension closed for modification"

    ReplyDelete
  2. ok thanks got the info from the next line
    "Its never a good idea to modify your already tested code to add new features".Sweet!

    ReplyDelete