Categories

Decorator Pattern Example

A while ago, I worked on a problem which is frequently encountered on some programming books and job interviews. The problem goes like this:

SALES TAXES

Basic sales tax is applicable at a rate of 10% on all goods, except books,
food, and medical products that are exempt. Import duty is an additional
sales tax applicable on all imported goods at a rate of 5%, with no
exemptions.

When I purchase items I receive a receipt which lists the name of all the
items and their price (including tax), finishing with the total cost of the
items, and the total amounts of sales taxes paid. The rounding rules for
sales tax are that for a tax rate of n%, a shelf price of p contains
(np/100 rounded up to the nearest 0.05) amount of sales tax.

Write an application that prints out the receipt details for these shopping
baskets…

INPUT:

Input 3:
1 imported bottle of perfume at 27.99
1 bottle of perfume at 18.99
1 packet of headache pills at 9.75
1 box of imported chocolates at 11.25

OUTPUT

Output 3:
1 imported bottle of perfume: 32.19
1 bottle of perfume: 20.89
1 packet of headache pills: 9.75
1 imported box of chocolates: 11.85
Sales Taxes: 6.70
Total: 74.68

The way the tax rate should be calculated for an item is determined on run-time, based on the properties of an item. This seemed like a problem domain that is suitable for using the decorator pattern. In this approach, I used a TaxCalculator that decorated the items on run-time, so that the items calculated their prices dynamically based on their properties. This is a simple domain model sketch to explain the idea:

Perhaps centralising the logic in a calculator object which would choose the strategy to be used to calculate the tax based on an item’s properties would normally come to one’s mind earlier than this approach but I think this approach is less boring :)

Using a decorator provided some more run-time flexibility (based on items in the Order) and also made it easier to extend and add new functionality by changing decorators’ behaviour or simply by adding more decorators. However, since the TaxCalculator uses the strategy pattern, it can later be replaced with a calculator that calculates the taxes itself after some refactoring.

The following class diagram describes how I used the decorator pattern to decorate Item objects:

You can find the source code at: http://github.com/erenay/sales-taxes-question

1 comment to Decorator Pattern Example

  • akhil

    Hi,
    I have a doubt. You have not given main method for any of the java classes…….. How can I run this program as a java application???

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>