samedi 1 août 2015

What to do if classes with same interface having similar but different method signature?

What to do if classes with same interface having similar but different method signature?

Let's say I have a project to calculate different costs (to get a total cost at last).

In my program, there is several calculator classes, namely ACostCalculator, BCostCalculator and so on. When a calculate() method is invoked to calculate a cost, a cost container is passed to those cost calculators to. In a good scenario, I can make a CostCalculator Interface for every cost calculators.

However, the calculation for different cost required different resources. In my current program, it make be like:

//getResource() are costly method while several costs need this. So do it outside calculate() method.
ResourceA resourceA = getResourceA(); 
ResourceB resourceB = getResourceB();

CostContainer costContainer = new CostContainer();
CostCalculator aCostCalculator = new ACostCalculator();
...
CostCalculator eCostCalculator = new ECostCalculator();

aCostCalculator.calculate(costContainer);
bCostCalculator.calculate(costContainer)
cCostCalculator.calculate(costContainer, resourceA);
dCostCalculator.calculate(costContainer, resourceA);
eCostCalculator.calculate(costContainer, resourceA, resourceB);

If the signature is exactly the same, I may make a loop conveniently to do it at once. However, since they are similar but different, I can't even make a good interface.

I am not sure if there is good ways to do so. What I can think of is generalizing all calculate() method to into

calculate(CostContainer costContainer, List<Object> resources);

Any ideas? Thanks for answering.

Aucun commentaire:

Enregistrer un commentaire