這裏是一個小的貨幣轉換的代碼:如何在java中爲通用轉換器擴展此設計?
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();
}
}
我想提高這個代碼,使其轉換不同的單位工作,例如:公斤到磅,英里公里,等等等等看起來像這樣的東西:
public class ConversionManager<T extends Convertible> {
public T convert(T c1, T c2)
{
//return null;
}
}
欣賞你的想法和建議。
謝謝你的回答。這裏有一個問題:getReferenceUnit()方法的重點是什麼? – Jay 2010-06-08 16:07:40
這個想法是,每個度量都有一個參考單位,每個其他單位根據參考單位定義它自己。在你最初的例子中,參考單位是美元,而其他貨幣是以美元換算的因數。我在這裏添加了getReferenceUnit()函數,只是爲了說明距離參考單位是米,因此千米單位實現將具有1000個轉換因子。 – bshields 2010-06-08 17:42:04