views:

90

answers:

3

Hello

I am thinking through a nice pattern to be useful across domains of measurable units (ie, Length, Time) and came up with the following use case and initial classes, and of course, questions!

1) Does a Composite pattern help or complicate?
2) Should the Convert method(s) in the ComposityNode be a separate converter class?

All comments appreciated. Cheers,
Berryl

Example Use Case:

var inch = new ConvertableUnit("inch", 1)
var foot = new ConvertableUnit("foot", 12)
var imperialUnits = new CompositeConvertableUnit("imperial units", .024)
imperialUnits.AddChild(inch)
imperialUnits.AddChild(foot)

var meter = new ConvertableUnit("meter", 1)
var millimeter = new ConvertableUnit("millimeter ", .001)
var imperialUnits = new CompositeConvertableUnit("metric units", 1)
imperialUnits.AddChild(meter)
imperialUnits.AddChild(millimeter)

var oneInch = new Quantity(1, inch);
var oneFoot = new Quantity(1, foot);
oneFoot.ToBase() //  "12 inches"

var oneMeter = new Quantity(1, meter);
oneInch.ToBase() //  .024 meters

Possible Solution

ConvertableUnit : Node  
  double Rate
  string Name

Quantity
  ConvertableUnit Unit
  double Amount

CompositeConvertableUnit : Node
  ISet<ConvertableUnit> _children
  ConvertableUnit BaseUnit {get{ return _children.Where(c=>c.Rate == 1).First() } } 
  Quantity ConvertTo(Quantity from, Quantity to)
  Quantity ToBase(Quantity from);
A: 

I don't really see any benefit to using the composite pattern here. From wikipedia:

Composite allows a group of objects to be treated in the same way as a single instance of an object.

You don't need groups of converter objects, a list of converters would be enough.

As for the Convert method - I would say converting is why the class exists, to probably a good place for it.

Oded
there is a bit of that though, I think. A composite of imperial length units, and a composite of metric length units could both be nodes in a composite of length. No? Do you see a better pattern for that?
Berryl
Composite was not the right pattern, and I did wind up with a Converter class after all. Cheers
Berryl
A: 

Martin Fowler has a very well thought out model for measurements and conversions and such in Analysis Patterns. Worth reviewing. I believe he recommended a Conversion Ratio object that would handle converting from one unit to another.

Chris Shaffer
Yeah, Fowler is the man, isn't he? Could you scratch out a C# implementation of his ratio class and how it might be used?
Berryl
+1  A: 

F# has a concept of units of measure built in, maybe you should look into the way they implemented it.

Mathias
I wonder why c# doesn't actually. I'm not familiar with f# but maybe a good excuse to look into it.
Berryl