|
||||||
Decorator Pattern ExampleA while ago, I worked on a problem which is frequently encountered on some programming books and job interviews. The problem goes like this:
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 |
||||||
|
Copyright © 2012 On the Road - All Rights Reserved |
||||||