• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Can some pattern help here?

 
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic