开发者

quantity of measurable units design pattern

开发者 https://www.devze.com 2022-12-27 16:09 出处:网络
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!

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

ConvertableU开发者_JAVA百科nit : 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);


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消