task1/solution02/src/org/apidesign/apifest08/currency/DefaultConvertorFactory.java
1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/task1/solution02/src/org/apidesign/apifest08/currency/DefaultConvertorFactory.java Sun Sep 28 14:12:38 2008 +0200
1.3 @@ -0,0 +1,49 @@
1.4 +package org.apidesign.apifest08.currency;
1.5 +
1.6 +
1.7 +import java.math.BigDecimal;
1.8 +import java.util.Currency;
1.9 +import java.util.HashMap;
1.10 +import java.util.Map;
1.11 +
1.12 +/**
1.13 + * Default factory for convertors. Basically it just keeps exchange rates for given currency combinations.
1.14 + * @author lukas
1.15 + *
1.16 + */
1.17 +class DefaultConvertorFactory {
1.18 + private static final Currency SKK = Currency.getInstance("SKK");
1.19 + private static final Currency USD = Currency.getInstance("USD");
1.20 + private static final Currency CZK = Currency.getInstance("CZK");
1.21 + private Map<String, Convertor> convertorMap = new HashMap<String, Convertor>();
1.22 +
1.23 + public DefaultConvertorFactory()
1.24 + {
1.25 + addConvertor(CZK,USD,BigDecimal.valueOf(17),BigDecimal.valueOf(1));
1.26 + addConvertor(CZK,SKK,BigDecimal.valueOf(80),BigDecimal.valueOf(100));
1.27 + }
1.28 +
1.29 + private void addConvertor(Currency sourceCurrency, Currency destinationCurrency, BigDecimal sourceEquivalent, BigDecimal destinationEquivalent) {
1.30 + DefaultConvertor convertor = new DefaultConvertor(sourceEquivalent, destinationEquivalent, sourceCurrency, destinationCurrency);
1.31 + convertorMap.put(getConvertorKey(sourceCurrency, destinationCurrency), convertor);
1.32 + convertorMap.put(getConvertorKey(destinationCurrency, sourceCurrency), convertor.revert());
1.33 + }
1.34 +
1.35 + public Convertor getConvertor(Currency sourceCurrency, Currency destinationCurrency) throws UnsupportedConversionException
1.36 + {
1.37 + String convertorKey = getConvertorKey(sourceCurrency, destinationCurrency);
1.38 + Convertor result = convertorMap.get(convertorKey);
1.39 + if (result!=null)
1.40 + {
1.41 + return result;
1.42 + }
1.43 + else
1.44 + {
1.45 + throw new UnsupportedConversionException("Conversion from "+sourceCurrency+" to "+destinationCurrency+" is not supported");
1.46 + }
1.47 + }
1.48 +
1.49 + private String getConvertorKey(Currency sourceCurrency, Currency destinationCurrency) {
1.50 + return sourceCurrency.getCurrencyCode()+destinationCurrency.getCurrencyCode();
1.51 + }
1.52 +}