task1/solution06/src/org/apidesign/apifest08/currency/ConvertorFactory.java
author japod@localhost
Sun, 28 Sep 2008 14:12:38 +0200
changeset 6 97662396c0fd
permissions -rw-r--r--
Adding solutions received for task1
     1 package org.apidesign.apifest08.currency;
     2 
     3 import static org.apidesign.apifest08.currency.Assert.notNull;
     4 
     5 import java.math.BigDecimal;
     6 import java.math.RoundingMode;
     7 import java.util.ArrayList;
     8 import java.util.Currency;
     9 import java.util.List;
    10 
    11 /**
    12  * The factory for {@link Convertor}.
    13  * 
    14  * @see #newInstance()
    15  */
    16 public final class ConvertorFactory {
    17 	//do not expose constructor
    18 	private ConvertorFactory(){}
    19 	
    20 	/**
    21 	 * @return a convertor instance. 
    22 	 *  
    23 	 * @throws CurrencyException in a convertor cannot be instantiated
    24 	 */
    25 	public static Convertor newInstance() throws CurrencyException{
    26 		return new DefaultConvertor();
    27 	}
    28 	
    29 	private static final class DefaultConvertor extends  Convertor {
    30 		private List<Bid> bids;
    31 		
    32 		private DefaultConvertor() {
    33 			bids = new ArrayList<Bid>();
    34 			Bid usdCzk = new Bid(Currencies.USD, Currencies.CZK, new BigDecimal("17"));
    35 			bids.add(usdCzk);
    36 			Bid skCzk = new Bid(Currencies.SKK, Currencies.CZK, new BigDecimal("0.8"));
    37 			bids.add(skCzk);
    38 		}
    39 		
    40 		@Override
    41 		public Amount convert(Amount from, Currency targetCurrency)
    42 				throws CurrencyException {
    43 			return convert(from.getValue(), from.getCurrency(), targetCurrency);
    44 			
    45 		}
    46 
    47 		@Override
    48 		public Amount convert(BigDecimal amount, Currency from,
    49 				Currency targetCurrency) throws ConversionException,
    50 				UnsupportedConversionException {
    51 			notNull(from, "from");
    52 			notNull(targetCurrency, "targetCurrency");
    53 			
    54 			int index = bids.indexOf(new Bid(from, targetCurrency));
    55 			if(index == -1) {
    56 				throw new UnsupportedConversionException(from, targetCurrency);
    57 			}
    58 			Bid bid = bids.get(index);
    59 			BigDecimal bidValue = bid.getBidValue(from, targetCurrency);
    60 			BigDecimal result = bidValue.multiply(amount);			
    61 			return new Amount(result, targetCurrency);
    62 		}
    63 
    64    }
    65 }