Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can some pattern help here?

 
Prasma Kankut
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Assume the following case:

The price to transport a shipment depends on 2 things
i) the distance from origin to destination and
ii) the weight of the shipment

For example,
If the transportation distance is less than 100 kms, the cost is 10$
If the transportation distance is between 100 and 200 kms, the cost is 20$
If the transportation distance is greater than 200 kms, the cost is 30$

If the shipment weight is less than 10 kgs, the cost is 10$
If the shipment weight is between 10 and 20 kgs, the cost is 20$
If the shipment weight is greater than 20 kgs, the cost is 30$

So, to transport a 50 kg shipment for 500 kms, the total cost is 60$.

Now, the shipment will have a getTotalCost() method, which will calculate the total cost, based on the above rules. It can be done with simple if/else checks, but ofcourse that is the worst way of doing.

Is there any pattern, which can help me here?

Strategy looks close, but I'm not sure. Any clues.

Many thanks
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I like Strategy but I almost always use fixed values to get a strategy from a map ... your ranges of values are a bit tougher.

For something this simple I'd probably just work through a collection of distance / rate pairs.

If you really must be objecty or if things got a bit more complex you could use a chain of widgets with this method:

I don't know if that's quite Chain Of Responsibility or not.

If your relationships are so neatly mathematical and you don't want to be at all objecty you could even do



Any other thoughts?
[ January 05, 2006: Message edited by: Stan James ]
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another "objecty" solution would be to replace

if distance < pair.distance

with

if pair.appliesTo(distance)

But it's most likely overkill, and easy to refactor to should it become valuable.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic