task1/solution06/src/org/apidesign/apifest08/currency/ConvertorFactory.java
changeset 6 97662396c0fd
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/task1/solution06/src/org/apidesign/apifest08/currency/ConvertorFactory.java	Sun Sep 28 14:12:38 2008 +0200
     1.3 @@ -0,0 +1,65 @@
     1.4 +package org.apidesign.apifest08.currency;
     1.5 +
     1.6 +import static org.apidesign.apifest08.currency.Assert.notNull;
     1.7 +
     1.8 +import java.math.BigDecimal;
     1.9 +import java.math.RoundingMode;
    1.10 +import java.util.ArrayList;
    1.11 +import java.util.Currency;
    1.12 +import java.util.List;
    1.13 +
    1.14 +/**
    1.15 + * The factory for {@link Convertor}.
    1.16 + * 
    1.17 + * @see #newInstance()
    1.18 + */
    1.19 +public final class ConvertorFactory {
    1.20 +	//do not expose constructor
    1.21 +	private ConvertorFactory(){}
    1.22 +	
    1.23 +	/**
    1.24 +	 * @return a convertor instance. 
    1.25 +	 *  
    1.26 +	 * @throws CurrencyException in a convertor cannot be instantiated
    1.27 +	 */
    1.28 +	public static Convertor newInstance() throws CurrencyException{
    1.29 +		return new DefaultConvertor();
    1.30 +	}
    1.31 +	
    1.32 +	private static final class DefaultConvertor extends  Convertor {
    1.33 +		private List<Bid> bids;
    1.34 +		
    1.35 +		private DefaultConvertor() {
    1.36 +			bids = new ArrayList<Bid>();
    1.37 +			Bid usdCzk = new Bid(Currencies.USD, Currencies.CZK, new BigDecimal("17"));
    1.38 +			bids.add(usdCzk);
    1.39 +			Bid skCzk = new Bid(Currencies.SKK, Currencies.CZK, new BigDecimal("0.8"));
    1.40 +			bids.add(skCzk);
    1.41 +		}
    1.42 +		
    1.43 +		@Override
    1.44 +		public Amount convert(Amount from, Currency targetCurrency)
    1.45 +				throws CurrencyException {
    1.46 +			return convert(from.getValue(), from.getCurrency(), targetCurrency);
    1.47 +			
    1.48 +		}
    1.49 +
    1.50 +		@Override
    1.51 +		public Amount convert(BigDecimal amount, Currency from,
    1.52 +				Currency targetCurrency) throws ConversionException,
    1.53 +				UnsupportedConversionException {
    1.54 +			notNull(from, "from");
    1.55 +			notNull(targetCurrency, "targetCurrency");
    1.56 +			
    1.57 +			int index = bids.indexOf(new Bid(from, targetCurrency));
    1.58 +			if(index == -1) {
    1.59 +				throw new UnsupportedConversionException(from, targetCurrency);
    1.60 +			}
    1.61 +			Bid bid = bids.get(index);
    1.62 +			BigDecimal bidValue = bid.getBidValue(from, targetCurrency);
    1.63 +			BigDecimal result = bidValue.multiply(amount);			
    1.64 +			return new Amount(result, targetCurrency);
    1.65 +		}
    1.66 +
    1.67 +   }
    1.68 +}