How to extend this design for a generic converter in java?
- by Jay
Here is a small currency converter piece of code:
public enum CurrencyType {
DOLLAR(1),
POUND(1.2),
RUPEE(.25);
private CurrencyType(double factor) {
this.factor = factor;
}
private double factor;
public double getFactor() {
return factor;
}
}
public class Currency {
public Currency(double value, CurrencyType type) {
this.value = value;
this.type = type;
}
private CurrencyType type;
private double value;
public CurrencyType getCurrencyType() {
return type;
}
public double getCurrencyValue() {
return value;
}
public void setCurrenctyValue(double value){
this.value = value;
}
}
public class CurrencyConversion {
public static Currency convert(Currency c1, Currency c2)
throws Exception {
if (c1 != null && c2 != null) {
c2.setCurrenctyValue(c1.getCurrencyValue()
* c1.getCurrencyType().getFactor()
* c2.getCurrencyType().getFactor());
return c2;
} else
throw new Exception();
}
}
I would like to improve this code to make it work for different units of conversion, for example: kgs to pounds, miles to kms, etc etc. Something that looks like this:
public class ConversionManager<T extends Convertible> {
public T convert(T c1, T c2)
{
//return null;
}
}
Appreciate your ideas and suggestions.