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