Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit converting design pattern in C#

I need to make conversions between units, each unit has 2 parts, its name and an integer, the integer part can be either positive or negative. I need my Unit class to have dependency injection and be loosely coupled. For example if I need to add something in the future, I don't want to have to change my other classes that are using this class.

There should be also a Convert() method in my unit class to convert between units. I took a look at these links:

  • Type Conversion in the .NET Framework
  • Pattern for Creating a Simple and Efficient Value type

But these seem loosely coupled.

Please let me know the recommended design pattern for this problem,

like image 887
Houshang.Karami Avatar asked Nov 03 '22 11:11

Houshang.Karami


1 Answers

I would create a custom attribute for methods that specifies the unit a method can convert to and from. Then your converter function can extract the unit from the items being converted and use reflection to find those classes with convert methods that convert to/from those units.

You do need a core unit of measurement that you use for your convert to/from methods. E.g. pick metric and then all conversions convert to/from metric to/from a second unit. Then to go from unit A to unit B, you convert from A to metric, then convert to B from metric, with A and B converters picked using reflection.

Of course, since you don't provide too much detail on your request, it is hard to tell what exactly you're trying to do so this is a wild guess "design". :)

like image 88
Tombala Avatar answered Nov 10 '22 06:11

Tombala