1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/task1/solution08/src/org/apidesign/apifest08/currency/Convertor.java Sun Sep 28 14:12:38 2008 +0200
1.3 @@ -0,0 +1,55 @@
1.4 +package org.apidesign.apifest08.currency;
1.5 +
1.6 +import java.util.Currency;
1.7 +import java.util.Hashtable;
1.8 +import java.util.Map;
1.9 +
1.10 +/** This is the skeleton class for your API. You need to make it public, so
1.11 + * it is accessible to your client code (currently in Task1Test.java) file.
1.12 + * <p>
1.13 + * Feel free to create additional classes or rename this one, just keep all
1.14 + * the API and its implementation in this package. Do not spread it outside
1.15 + * to other packages.
1.16 + */
1.17 +public class Convertor {
1.18 +
1.19 + private static final Map<String, Float> EXCHANGE_RATES = new Hashtable<String, Float>() { {
1.20 + put("CZKUSD", 1/17F);
1.21 + put("USDCZK", 17F);
1.22 + put("SKKCZK", 100/80F);
1.23 + put("CZKSKK", 80/100F);
1.24 + }
1.25 + };
1.26 +
1.27 + private Currency currencyFirst;
1.28 + private Currency currencySecond;
1.29 +
1.30 + private Convertor(Currency currencyFirst, Currency currencySecond) {
1.31 + this.currencyFirst = currencyFirst;
1.32 + this.currencySecond = currencySecond;
1.33 + }
1.34 +
1.35 + public static Convertor getInstanceFor(Currency currencyFirst, Currency currencySecond) {
1.36 + return new Convertor(currencyFirst, currencySecond);
1.37 + }
1.38 +
1.39 + public float convert(float value, Currency toCurrency) {
1.40 + if (!toCurrency.equals(currencyFirst) && !toCurrency.equals(currencySecond)) {
1.41 + throw new IllegalArgumentException("Unsupported currency for this convertor!: " + toCurrency.getCurrencyCode());
1.42 + }
1.43 +
1.44 + Float rate = null;
1.45 + if (toCurrency.equals(currencyFirst)) {
1.46 + rate = EXCHANGE_RATES.get(currencyFirst.getCurrencyCode() + currencySecond.getCurrencyCode());
1.47 + }
1.48 + if (toCurrency.equals(currencySecond)) {
1.49 + rate = EXCHANGE_RATES.get(currencySecond.getCurrencyCode() + currencyFirst.getCurrencyCode());
1.50 + }
1.51 +
1.52 + if (rate == null) {
1.53 + throw new IllegalStateException("Undefinied conversion!");
1.54 + }
1.55 +
1.56 + return rate*value;
1.57 + }
1.58 +}