views:

90

answers:

1

Hi all I want to develop a system that is similar to calculation of salary. A salary has a basic value. On top of it, an employee can get some Bonus (es) or Penalties. Decorator Pattern seems to fit this scenario

Salary finalSalary = new HardworkBonus(new LateComingPenalty(new BasicSalary()))
System.out.println("Your total salary is : "+ finalSalary.calculate())

In addition, I want to save the result of each computation. So in the end, even after calculation, I can retrieve how much was the LateComingPenalty.

It seems to be a common problem where such sort of invoice calculations is involved.There might be some better options than Decorator Pattern.Do you have some better suggestions?

+6  A: 

That seems like a bit of overengineering. I might suggest:

class Salary {
    double base;
    SalaryAdjustment[] adjustments;
    double getSalary() {
        double r = base;
        for (SalaryAdjustment a: adjustments) {
            r += a.getAdjustment();
        }
        return r;
    }
};

In adjustments you can add your HardworkBonus and LatePenalty or whatever else, and retrieve them later.

Greg Hewgill
+1 for the overengineering comment. Sometimes the decorator pattern is really horrible
RichardOD
Probably best to use an arbitrary precision type like BigDecimal for a monetary amount.
matt b
Thanks for the answer but wouldn't it miss the "on top of" affect. Perhaps I over simplified the problem. Each component operates on some basis which is not necessarily the base salary. For e.g, if we have Base Salary, First Bonus = 2% of Base, Second Bonus = 1% of First Bonus, Damage Penalty = 1% of Base, Late Penalty = 10% of running sum till now, Income Tax = 16% of sum etc. Thus order of calculation is important and calculation should be performed once. I can initialize SalaryAdjustment with basis of calculation but then the calc need to be performed more than once.
anergy